JavaScript clearInterval()

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() Syntax and Return Value Top ↑

clearInterval(intervalId);

clearInterval() returns undefined. Keep the ID from setInterval() in a variable that your stop logic can access.

Start and Stop a Repeating Task Top ↑

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.

Prevent Multiple Intervals from Stacking Top ↑

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);

Timer IDs and Matching APIs Top ↑

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.

Clear Timers When a UI No Longer Needs Them Top ↑

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.

Common clearInterval() Mistakes Top ↑

  • Not storing the interval ID.
  • Overwriting the ID before clearing the old interval.
  • Starting duplicate intervals.
  • Clearing the wrong timer variable.
  • Assuming clearing an interval resets application state; it only stops future callbacks.

Related window examples: JavaScript redirect.

setInterval() setTimeout()




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer