Reconnection with exponential backoff:
1class ReconnectingWebSocket {2 private ws: WebSocket;3 private retryCount = 0;4 private maxRetries = 10;56 connect(url: string) {7 this.ws = new WebSocket(url);89 this.ws.onclose = () => {10 if (this.retryCount < this.maxRetries) {11 const delay = Math.min(1000 * Math.pow(2, this.retryCount), 30000);12 setTimeout(() => {13 this.retryCount++;14 this.connect(url);15 }, delay);16 }17 };1819 this.ws.onopen = () => {20 this.retryCount = 0; // reset on success21 };22 }23}
Considerations: