Skip to content

Commit 75e27cf

Browse files
Copilotkevinelliott
andcommitted
Fix reconnection bugs: prevent memory leaks and stack overflow
Co-authored-by: kevinelliott <123112+kevinelliott@users.noreply.github.com>
1 parent 0489736 commit 75e27cf

2 files changed

Lines changed: 34 additions & 23 deletions

File tree

cmd/web/script.js

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -225,32 +225,43 @@ function connectWebSocket() {
225225
document.getElementById('status-text').textContent = 'Connection lost - attempting to reconnect...';
226226
}
227227

228+
// Clear any existing reconnection timer to prevent memory leaks
229+
if (wsReconnectInterval) {
230+
clearTimeout(wsReconnectInterval);
231+
wsReconnectInterval = null;
232+
}
233+
228234
// Set up reconnection with exponential backoff
229-
if (!wsReconnectInterval) {
230-
let reconnectAttempts = 0;
231-
let delay = 1000; // Start with 1 second
232-
233-
const attemptReconnect = () => {
234-
reconnectAttempts++;
235-
const maxAttempts = 30;
236-
237-
if (reconnectAttempts > maxAttempts) {
238-
wsReconnectInterval = null;
239-
document.getElementById('status-text').textContent = 'Connection failed - please refresh the page';
240-
return;
241-
}
235+
let reconnectAttempts = 0;
236+
let delay = 1000; // Start with 1 second
237+
238+
const attemptReconnect = () => {
239+
reconnectAttempts++;
240+
const maxAttempts = 30;
241+
242+
if (reconnectAttempts > maxAttempts) {
243+
wsReconnectInterval = null;
244+
document.getElementById('status-text').textContent = 'Connection failed - please refresh the page';
245+
return;
246+
}
242247

243-
console.log('Reconnect attempt ' + reconnectAttempts + '/' + maxAttempts + ' (delay: ' + delay + 'ms)');
244-
document.getElementById('status-text').textContent = 'Reconnecting (' + reconnectAttempts + '/' + maxAttempts + ')...';
245-
connectWebSocket();
246-
247-
// Double the delay for next attempt, cap at 30 seconds
248-
delay = Math.min(delay * 2, 30000);
249-
wsReconnectInterval = setTimeout(attemptReconnect, delay);
250-
};
248+
console.log('Reconnect attempt ' + reconnectAttempts + '/' + maxAttempts + ' (delay: ' + delay + 'ms)');
249+
document.getElementById('status-text').textContent = 'Reconnecting (' + reconnectAttempts + '/' + maxAttempts + ')...';
250+
251+
// Close existing WebSocket if it exists to avoid resource leaks
252+
if (ws) {
253+
ws.onclose = null; // Remove handler to prevent triggering another reconnection
254+
ws.close();
255+
}
256+
257+
connectWebSocket();
251258

259+
// Double the delay for next attempt, cap at 30 seconds
260+
delay = Math.min(delay * 2, 30000);
252261
wsReconnectInterval = setTimeout(attemptReconnect, delay);
253-
}
262+
};
263+
264+
wsReconnectInterval = setTimeout(attemptReconnect, delay);
254265
};
255266
}
256267

0 commit comments

Comments
 (0)