Forgotten Timers and Intervals
What you'll learn: How setInterval and setTimeout can create memory leaks if you never clear them, and how to properly manage their lifecycle.
Why Timers Prevent Garbage Collection
When you call setInterval or setTimeout, JavaScript keeps a reference to the callback function and any variables it closes over. Even if the original context (like a component or object) is no longer needed, the timer keeps everything alive because it still needs to execute that callback in the future.
Think of it like subscribing to a magazine. Even if you move away or lose interest, the magazines keep coming (and you keep paying) until you explicitly cancel the subscription.
function createLeakyWidget() {
const hugeData = new Array(1000000).fill('data');
// This timer keeps hugeData alive forever!
setInterval(() => {
console.log('Checking...', hugeData.length);
}, 1000);
}
createLeakyWidget();
// hugeData can never be garbage collected
// because the interval still references it
Proper Timer Lifecycle Management
Always store the timer ID and clear it when you're done:
function createSafeWidget() {
const hugeData = new Array(1000000).fill('data');
const timerId = setInterval(() => {
console.log('Checking...', hugeData.length);
}, 1000);
// Return a cleanup function
return function cleanup() {
clearInterval(timerId);
// Now hugeData can be garbage collected
};
}
const cleanup = createSafeWidget();
// Later, when done:
cleanup();
The same principle applies to setTimeout — even though it runs once, it keeps references alive until it executes (or is cleared).
Key Takeaway: Always call clearInterval and clearTimeout when timers are no longer needed; forgotten timers hold references that prevent garbage collection, creating memory leaks.