Exponential backoff with jitter

let delay = 1000;
let attempts = 0;
function connect() {
  const ws = new WebSocket(url);
  ws.onclose = () => {
    attempts++;
    delay = Math.min(30000, delay * 2) + Math.random() * 1000;
    setTimeout(connect, delay);
  };
  ws.onopen = () => { attempts = 0; delay = 1000; };
}
Advertisement

Distinguish close codes

1000 (normal), 1001 (going away), 1006 (abnormal, likely network). Only reconnect on 1006 and unusual codes.

Advertisement

Resume vs restart

Some protocols support resume with a last-event-id. Otherwise, restart from scratch.