Keep a counter running until the user clicks Stop.
JavaScript
// Imagine buttons: Start / Stop and <pre id="out">
let id = null;
let n = 0;
function start() {
if (id !== null) return;
id = setInterval(function () {
n += 1;
document.getElementById("out").textContent = String(n);
}, 400);
}
function stop() {
clearInterval(id);
id = null;
}
Always store real IDs from setInterval in practice.
Compatibility
Browser Support
Window.clearInterval() is marked Baseline Widely available on MDN (since July 2015). Also available in workers.
✓ Baseline · Widely available
clearInterval()
Cancel repeating setInterval timers across modern browsers.
99%Core tag support
ChromeYes
Full support
EdgeYes
Full support
FirefoxYes
Full support
SafariYes
Full support
OperaYes
Full support
HTML element100% supported
Bottom line: Safe for production. Always clear intervals you no longer need.
Frequently Asked Questions
It cancels a repeating timer previously started with setInterval(). After you clear that ID, the callback will not run again unless you create a new interval.
No. MDN marks Window.clearInterval() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
The interval ID returned by setInterval(). Store that ID in a variable so you can pass it later.
undefined. It cancels the timer as a side effect; there is no useful return value.
Technically yes — setInterval and setTimeout share one ID pool, so clearInterval and clearTimeout can cancel either. Prefer matching names for clarity.
clearInterval() does nothing. Calling it twice or with an unknown ID is safe.