07 · Senior Frontend Engineering
mediumcodingjavascript~10 min

WebSocket Reconnect Delays

Objective: Compute safe reconnect delays: exponential growth, a cap, and randomisation.

Write `nextDelay(attempt, { baseMs, maxMs, random })` using exponential backoff with full jitter, so thousands of clients do not reconnect in lockstep after an outage.

  • The ceiling for attempt n (0-based) is `min(maxMs, baseMs * 2 ** n)`.
  • The delay is `Math.floor(random() * (ceiling + 1))`, where `random` returns [0, 1).
  • Defaults: baseMs 500, maxMs 30000, random Math.random.
  • Never return a negative number or exceed maxMs; reject invalid attempts (negative or non-integer) with a RangeError.
JavaScript

⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor

Output
> Nothing has run yet.
Interview follow-up questions
  • What is the difference between full jitter and equal jitter?
  • When should the attempt counter reset?
  • How do you avoid reconnecting while the tab is hidden or offline?