title: WebSocket: How to automatically reconnect after it dies
body: <pre><code>var ws = new WebSocket('ws://localhost:8080');
  ws.onopen = function () {
    ws.send(JSON.stringify({
        .... some message the I must send when I connect ....
    }));
  
  };
  
  ws.onmessage = function (e) {
    console.log('Got a message')
    console.log(e.data);
  };
  
  ws.onclose = function(e) {  
    console.log('socket closed try again'); 
  
  }
  
  ws.onerror = function(err) {
    console.error(err)
  };
  </code></pre>
  
  <p>When I first connect to the socket, I must first send a message to the server to authenticate myself and subscribe to channels.</p>
  
  <p>The problem I have is that sometimes the socket server is unreliable and that triggers the <code>onerror</code> and <code>onclose</code> events of the <code>'ws'</code> object. </p>
  
  <p>Question: What is a good design pattern that would allow me, whenever the socket closes or encounters an error, wait for 10 seconds and then reconnect to the socket server (and resend the initial message to the server)</p>