Window clearInterval() 方法
实例
显示当前时间 ( setInterval() 函数会每秒执行一次函数,类似手表)。使用 clearInterval() 来停止执行:
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);
}
定义和用法
clearInterval() 方法可取消由 setInterval() 函数设定的定时执行操作。
clearInterval() 方法的参数必须是由 setInterval() 返回的 ID 值。
注意: 要使用 clearInterval() 方法, 在创建执行定时操作时要使用全局变量:
myVar = setInterval("javascript 函数", milliseconds);
你可以通过 clearInterval() 方法来停止执行。
浏览器支持
表格中的数字表示支持该属性的第一个浏览器版本号。
| 方法 | |||||
|---|---|---|---|---|---|
| clearInterval() | 1.0 | 4.0 | 1.0 | 1.0 | 4.0 | 
语法
clearInterval(id_of_setinterval)
| 参数 | 描述 | 
|---|---|
| id_of_setinterval | 调用 setInterval() 函数时所获得的返回值,使用该返回标识符作为参数,可以取消该 setInterval() 所设定的定时执行操作。 | 
技术细节
| 返回值: | 没有返回值。 | 
|---|
更多实例
实例
每 300 毫秒切换背景颜色,直到通过 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);
}
实例
使用 setInterval() 和 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 + '%'; 
    }
  }
}
相关页面
Window 对象: setInterval() 方法
Window 对象: setTimeout() 方法
Window 对象: clearTimeout() 方法

 Window 对象
 Window 对象