Easy Tutorial
❮ Met Element Getelementsbytagname Jsref Number ❯

Window clearInterval() Method

Window Object

Example

Display the current time (the setInterval() function executes the function every second, similar to a watch). Use clearInterval() to stop the execution:

var myVar = setInterval(function(){ myTimer() }, 1000);

function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
    clearInterval(myVar);
}

Definition and Usage

The clearInterval() method cancels the timed, repeated execution set by setInterval().

The parameter for the clearInterval() method must be the ID value returned by setInterval().

Note: To use the clearInterval() method, you must use a global variable when creating the timed action:

myVar = setInterval("javascript function", milliseconds);

You can stop the execution by using the clearInterval() method.


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method Chrome IE Firefox Safari Opera
clearInterval() 1.0 4.0 1.0 1.0 4.0

Syntax

clearInterval(id_of_setinterval)
Parameter Description
id_of_setinterval The value returned by the setInterval() function, used to identify and cancel the timed action.

Technical Details

| Return Value: | No return value. | | --- | --- |


More Examples

Example

Toggle the background color every 300 milliseconds until stopped with clearInterval():

var myVar = setInterval(function(){ setColor() }, 300);

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

function stopColor() {
    clearInterval(myVar);
}

Example

Create a dynamic progress bar using setInterval() and clearInterval():

function move() {
  var elem = document.getElementById("myBar"); 
  var width = 0;
  var id = setInterval(frame, 100);
  function frame() {
    if (width == 100) {
      clearInterval(id);
    } else {
      width++; 
      elem.style.width = width + '%'; 
    }
  }
}

Related Pages

Window Object: setInterval() Method

Window Object: setTimeout() Method

Window Object: clearTimeout() Method

Window Object

❮ Met Element Getelementsbytagname Jsref Number ❯