title: How to ensure code is always called before page unload
body: <p>Usually this isn't important, and it may not even be too important for my situation, but I'd like to know if there is a reasonable way to implement this. </p>
  
  <p>My page automatically opens a web socket connection. In order to be a better client I want the client to clean up after itself and close the websocket before the page gets unloaded. </p>
  
  <p>My hope is that the browser would have the foresight to call <code>close()</code> for me when the page is unloaded, but in case it doesn't, how can I leverage the <code>onbeforeunload</code> message (or some such) to do some "final cleanup" (not unlike <code>atexit()</code> in C)? </p>
  
  <p>Suppose I have some system where I want my clients to send an "exiting" message to my websocket server for some reason. </p>
  
  <p>I can do this now: </p>
  
  <pre><code>$(window).on('beforeunload', function () {
      websocket.close(); // websocket is a WebSocket
  });
  </code></pre>
  
  <p>But suppose <code>close()</code> is actually an asynchronous call (is it?) and I want to <strong>make sure</strong> the socket.onclose callback fires prior to actually unloading the page! Can this be done? </p>