WebSocket with reconnect

Reconnect with a growing delay and send a ping so dead connections are noticed.

AJAX · WebSocket with reconnectAdvanced
function connect(url, onMessage) {
  let ws, tries = 0, pingTimer;

  function open() {
    ws = new WebSocket(url);
    ws.onopen = function () { tries = 0; pingTimer = setInterval(() => ws.readyState === 1 && ws.send('ping'), 25000); };
    ws.onmessage = function (e) { if (e.data !== 'pong') onMessage(JSON.parse(e.data)); };
    ws.onclose = function () {
      clearInterval(pingTimer);
      setTimeout(open, Math.min(30000, 1000 * 2 ** tries++));
    };
  }
  open();
  return { send: (obj) => ws.readyState === 1 && ws.send(JSON.stringify(obj)), close: () => { ws.onclose = null; ws.close(); } };
}
websocketrealtimereconnectheartbeat