Course contentsShow
← JavaScript
Lesson 530 of 2,72313. ClosuresFree lesson

Closures in Timers and Intervals

How setTimeout and setInterval callbacks keep their closure scope alive until cleared.

Closures in Timers and Intervals

What You'll Learn

You'll discover how setTimeout and setInterval callbacks preserve their closure scope even after the outer function finishes, and why that closure stays alive until you clear the timer.

Why Timer Closures Persist

When you pass a function to setTimeout or setInterval, JavaScript keeps that function—and its entire closure—alive in memory until the timer fires or is cleared. This happens because the timer mechanism holds a reference to your callback function.

Think of it like leaving a note in a time capsule: even though you walk away, the capsule preserves your note (and everything it references) until someone opens it later.

The Lifecycle

When you create a timer:

  1. Your callback function is registered with the timer
  2. The outer function may finish and return
  3. But the timer still holds onto your callback
  4. Your callback's closure remains intact, keeping captured variables alive
  5. When the timer fires, the callback runs with its original closure
  6. Only after clearTimeout/clearInterval (or after a setTimeout fires) does the closure get released

Example Pattern

function startCounter(name) {
  let count = 0;
  
  const id = setInterval(() => {
    count++;
    console.log(`${name}: ${count}`);
  }, 1000);
  
  return id; // outer function returns, but closure lives on
}

const timerId = startCounter("MyTimer");
// Even though startCounter finished, the callback
// still has access to 'name' and 'count'

// Later: stop the timer and free the closure
clearInterval(timerId);

The count and name variables stay in memory as long as the interval keeps running, because the callback closure needs them.

Key Takeaway: Timer callbacks preserve their closure scope for as long as the timer exists—this keeps captured variables alive until you call clearTimeout or clearInterval, which is essential for stateful timers but can cause memory leaks if forgotten.