Timer cleanup
Learn to prevent memory leaks by cleaning up timers when an element is removed.
Memory leaks and cleanup
Even after an element is removed from the page, a timer attached to it can keep running. This leads to wasted memory, that is, a memory leak. To stop the timer you must store its id and call clearInterval or clearTimeout at the right moment.
const id = setInterval(() => {
console.log('Running');
}, 1000);
// when the element is removed:
clearInterval(id);Here id is stored and cleaned up with clearInterval(id) when the element is removed. Otherwise the callback tries to reach an element that no longer exists.
Cleanup inside an event handler
You can do timer cleanup inside event handlers. For example, when a stop button is clicked you call clearInterval. This way the user stops the timer at any moment.
const id = setInterval(() => {
console.log('Running');
}, 500);
stopBtn.addEventListener('click', () => {
clearInterval(id);
});Here every click on the button calls clearInterval(id) and stops the timer. The same pattern applies to requestAnimationFrame; you call cancelAnimationFrame when you want to stop.
Exercise Stop the interval on button click
Add a stop button to the setInterval below: when the #stop button is clicked, call clearInterval(id).
Show example solution
const stopBtn = document.querySelector('#stop');
let count = 0;
const id = setInterval(() => {
count = count + 1;
console.log(count);
}, 500);
stopBtn.addEventListener('click', () => {
clearInterval(id);
});
Test yourself
-
Which of the following causes a memory leak?
- storing the setInterval id
- not calling clearInterval
- using let instead of const
- using an arrow function
Show answer
not calling clearInterval — Correct! Without clearInterval the timer keeps running and memory leaks.
-
Complete the cleanup line
const id = setInterval(() => { counter.textContent = count; }, 1000); // when the element is removed: ____(id);Show answer
const id = setInterval(() => { counter.textContent = count; }, 1000); // when the element is removed: clearInterval(id); -
Match the cleanup patterns
- clearInterval(id)
- stops a repeating timer
- clearTimeout(id)
- cancels a one-shot timer
- cancelAnimationFrame(id)
- cancels an animation frame
- stopBtn.addEventListener('click', ...)
- cleans up on button click