JavaScript › Memory Management & Garbage Collection
Why can setInterval() be a subtle source of memory leaks, and how do you avoid it?
AdvancedAnswer
A running setInterval() keeps its callback (and everything it closes over) alive indefinitely until clearInterval() is called — if the component or context that started it is destroyed without ever clearing the interval, the callback and its retained scope leak for the rest of the page's lifetime.
function startPolling() {
const largeState = loadInitialState();
const id = setInterval(() => checkStatus(largeState), 1000);
return () => clearInterval(id); // must be called on cleanup
}Real-world example A React component that starts a setInterval() in useEffect but forgets to return a cleanup function calling clearInterval().