title: Implementing a loading spinner
body: <p>I am trying to implement a loading spinner in rails 5. The spinner is suposed to appear and spin when an object is deleted from a table view (also deleted from the database). The delete action is being handled in a file called destroy.js.erb. The problem is that I specified the sequence of events to be:
  1. Show the spinner
  2. delete from the database
  3. send a notification email
  4. hide the spinner</p>
  
  <p>But for some reason when I press the delete button, steps 2 and 3 happen first and then 1 happens. Even though the order is clear!</p>
  
  <p>If I remove the delete and send functions (which are handled in rails), the javascript order executes correctly (for example just to show and then hide the spinner immediately). But as soon as there is a rails operation between step 1 and 4, the order is messed up.</p>
  
  <p>I have already tried several things that did not work:</p>
  
  <ol>
  <li><p>I tried running the rails operations inside the destroy controller then render destroy.js.erb to show and hide the spinner (obviously did not work because it will always run ruby first)</p></li>
  <li><p>I tried to do everything in the js.erb file, by specifying the order mentioned above and using embedded ruby for the operations... also did not work because the ruby code is always executed first.</p></li>
  </ol>
  
  <p>Any help would be appretiated.</p>
  
  <p>Here is the code for my destroy.js.erb:</p>
  
  <pre><code>$("#spinner").show();
  
  $("#internal_request_&lt;%= @request.id %&gt;").remove();
  
  "&lt;%@request.destroy%&gt;";
  
  "&lt;%CancelRequestMailer.cancel_request_email(@current_requester, @recipients, @request).deliver%&gt;";
  
  $("#spinner").hide();
  
  </code></pre>
  
  <p>Here is the code for application.js</p>
  
  <pre><code>//= require rails-ujs
  //= require turbolinks
  //= require_tree .
  //= require jquery
  
  $( document ).ready(function() {
  
    // hide spinner
    $("#spinner").hide();
  });
  </code></pre>
  
  <p>Here is the html.erb for the button</p>
  
  <pre class="lang-rb prettyprint-override"><code>&lt;%= link_to request, :method =&gt; :delete, data: {:confirm =&gt; "Are you sure?"}, remote: true do %&gt;
    &lt;button type="button" class="btn btn-outline-danger"&gt;
      &lt;i class="fas fa-ban fa-fw"&gt;&lt;/i&gt;
    &lt;/button&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>Again... All this is working... It is just that the order is wrong... The spinner only appears when everything is already done (deletion, email sent..)</p>
  
  <p>It should appear before and stay while the operations are being performed and then go away.</p>