clearInterval() stops a repeating timer that was started by setInterval(). Pass it the interval ID returned by setInterval().
const intervalId = setInterval(task, 1000);
clearInterval(intervalId);
Calling clearInterval() with an ID that is not active simply has no effect.
clearInterval(intervalId);
clearInterval() returns undefined. Keep the ID from setInterval() in a variable that your stop logic can access.
let intervalId = null;
function start() {
if (intervalId !== null) return;
intervalId = setInterval(() => console.log("tick"), 1000);
}
function stop() {
clearInterval(intervalId);
intervalId = null;
}
The existing clearInterval demo shows the same start/stop idea.
A common bug is starting a new interval on every click. Guard against an already-running timer or clear it before starting another one.
if (intervalId !== null) {
clearInterval(intervalId);
}
intervalId = setInterval(updateClock, 1000);
setInterval() and setTimeout() use the same underlying pool of timer IDs in browsers. Although the clearing APIs can technically accept IDs from either pool, matching clearInterval() with setInterval() and clearTimeout() with setTimeout() makes code easier to understand.
Stop recurring work when a component, dialog, view, or activity is removed. This avoids unnecessary CPU work and prevents callbacks from trying to update elements that no longer exist.
Related window examples: JavaScript redirect.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.