Advertisement
Advanced JavaScript, Memory Management & Garbage Collection

Why can setInterval() be a subtle source of memory leaks, and how do you avoid it?

Short answer

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…

Save JavaScript mock interview
Advertisement
AModel answer
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().
Likely follow-ups
  • Does the same leak risk apply to setTimeout() used for repeated polling via re-scheduling itself?
Related topics