title: Javascript: wait until ajax request finishes to close page
body: <p>I would like the browser to keep the page open until the ajax requests are sent. This is what I imagine it would look like</p>
  
  <pre><code>var requestsPending = 0;
  
  window.onbeforeunload = function() {
      showPleaseWaitMessage();
      while(requestsPending &gt; 0);
  }
  
  // called before making ajax request, atomic somehow
  function ajaxStarted() {
      requestsPending++;
  }
  // called when ajax finishes, also atomic
  function ajaxFinished() {
      requestsPending--;
  }
  </code></pre>
  
  <p>Unfortunately, JS doesn't do multi-threading. To my understanding, the callback (ajaxFinished) would never be executed because the browser would try to wait until the while loop finishes to execute it, and so the it would loop forever.</p>
  
  <p>What's the right way to do this? Is there maybe a way to force JS to evaluate the next thing in its to-do list and then come back to the while loop? Or some syntax to "join" with an ajax call? I'm using DWR for my ajax.</p>
  
  <p>Thanks,
  -Max</p>