Course contentsShow
← Web Development
Lesson 2112 of 2,98238. JavaScript Performance in the BrowserFree lesson

Timers and Intervals Without Cleanup

Learn how setInterval and setTimeout can cause leaks if not properly cleared when components unmount.

Timers and Intervals Without Cleanup

You'll learn how forgotten timers and intervals keep running invisibly, holding memory hostage and causing performance degradation.

The Core Problem

When you create a timer with setTimeout() or a repeating interval with setInterval(), JavaScript registers a callback function that must be kept in memory until it executes (or repeats). If you create these timers in a component or function that later "unmounts" or gets cleaned up—but you don't explicitly clear the timer—JavaScript can't garbage collect the associated callback or any variables it references.

Think of it like this: You set an alarm clock in a hotel room, then check out. The alarm keeps ringing, the hotel can't clean the room, and your stuff stays there indefinitely because the system thinks you're still using it.

How It Happens

function startPolling() {
  const data = { userId: 12345, largeArray: new Array(10000) };
  
  setInterval(() => {
    console.log('Polling for user:', data.userId);
  }, 5000);
  
  // Function ends, but interval keeps running forever
  // 'data' is retained in memory because the callback references it
}

startPolling(); // Called once, creates a permanent leak

Even though startPolling() finishes executing, the interval callback holds a reference to data through closure. That memory can never be freed.

The Solution Pattern

Always store timer IDs and clear them during cleanup:

let timerId;

function startPolling() {
  timerId = setInterval(() => {
    console.log('Polling...');
  }, 5000);
}

function cleanup() {
  clearInterval(timerId);
}

Key Takeaway: Always pair setTimeout/setInterval with clearTimeout/clearInterval in your cleanup logic—memory leaks from forgotten timers accumulate silently and can severely degrade performance over time.