Window clearInterval()

Example

Display the time once every second. Use clearInterval() to stop the time:

const myInterval = setInterval(myTimer, 1000);

function myTimer() {
  const date = new Date();
  document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}

function myStopFunction() {
  clearInterval(myInterval);
}
Try it Yourself »

More examples below.


Description

The clearInterval() method clears a timer set with the setInterval() method.

Note

To clear an interval, use the id returned from setInterval():

myInterval = setInterval(function, milliseconds);

Then you can to stop the execution by calling clearInterval():

clearInterval(myInterval);

See Also:

The setInterval() Method

The setTimeout() Method

The clearTimeout() Method


Syntax

clearInterval(intervalId)

Parameters

Parameter Description
intervalId Required.
The interval id returned from setInterval().

Return Value

NONE


More Examples

Toggle between two background colors once every 500 milliseconds:

const myInterval = setInterval(setColor, 500);

function setColor() {
  let x = document.body;
  x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}

function stopColor() {
  clearInterval(myInterval);
}
Try it Yourself »

Using setInterval() and clearInterval() to create a dynamic progress bar:

function move() {
  const element = document.getElementById("myBar");
  let width = 0;
  const id = setInterval(frame, 100);
  function frame() {
    if (width == 100) {
      clearInterval(id);
    } else {
      width++;
      element.style.width = width + '%';
    }
  }
}
Try it Yourself »

Browser Support

clearInterval() is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.