Skip to content

Commit

Permalink
Exponential backoff with useRef
Browse files Browse the repository at this point in the history
  • Loading branch information
ProjectMoon committed Aug 1, 2024
1 parent 84821d2 commit 963be36
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions ui/components/ChatWindow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ const useSocket = (
hasError: boolean
) => {
const [ws, setWs] = useState<WebSocket | null>(null);
const reconnectTimeout = useRef(0);
const reconnectAttempts = useRef(0);

useEffect(() => {
if (!ws) {
Expand Down Expand Up @@ -182,6 +184,8 @@ const useSocket = (

ws.onopen = () => {
console.log('[DEBUG] open');
reconnectTimeout.current = 0;
reconnectAttempts.current = 0;
clearTimeout(timeoutId);
setError(false);
setIsWSReady(true);
Expand All @@ -195,7 +199,7 @@ const useSocket = (

ws.onclose = () => {
clearTimeout(timeoutId);
if (!hasError) {
if (!hasError && reconnectAttempts <) {
setWs(null); // forces websocket to reopen when needed.
}
console.log('[DEBUG] closed');
Expand All @@ -211,7 +215,15 @@ const useSocket = (
setWs(ws);
};

connectWs();
if (reconnectAttempts.current < 3) {
console.log(`[DEBUG] Attempting to reconnect (${reconnectAttempts.current + 1}/3)`);
setTimeout(connectWs, reconnectTimeout.current);
reconnectTimeout.current = reconnectTimeout.current > 0 ? reconnectTimeout.current * 2 : 1000;
reconnectAttempts.current += 1;
} else {
console.log('[DEBUG] WebSocket reconnect failure after 3 retries');
setError(true);
}
}

return () => {
Expand Down

0 comments on commit 963be36

Please sign in to comment.