Window clearInterval() 方法
实例
显示当前时间( setInterval() 方法将每 1 秒执行一次 "myTimer" 函数)。
使用 clearInterval() 停止时间:
<!DOCTYPE html><html><body><p>此页上的脚本启动此时钟:</p><p id="demo"><button onclick="myStopFunction()">停止</button><script>var myVar = setInterval(myTimer, 1000);function myTimer() {var d = new Date();var t = d.toLocaleTimeString();document.getElementById("demo").innerHTML = t;}function myStopFunction() {clearInterval(myVar);}</script></body></html>
定义与用法
clearInterval() 方法清除使用 setInterval() 方法设置的计时器。
setInterval() 返回的 ID 值用作 clearInterval() 方法的参数。
注意:为了能够使用 clearInterval() 方法,在创建 interval 方法时必须使用变量:
myVar = setInterval("javascript function", milliseconds);
然后可以通过调用 clearInterval() 方法停止执行。
clearInterval(myVar);
浏览器支持
表中的数字指定完全支持该方法的第一个浏览器版本。
| 方法 | |||||
|---|---|---|---|---|---|
| clearInterval() | 1.0 | 4.0 | 1.0 | 1.0 | 4.0 |
语法
clearInterval(var)
参数值
| 参数 | 描述 |
|---|---|
| var | 必填。setInterval() 方法返回的计时器的名称 |
技术细节
| 返回值: | 无返回值 |
|---|
更多实例
实例
每 300 毫秒在两种背景色之间切换一次,直到 clearInterval() 停止:
<!DOCTYPE html><html><body><p>在本例中,setInterval() 方法每 300 毫秒执行一次 setColor() 函数,该函数将在两种背景色之间切换。</p><button onclick="stopColor()">停止切换</button><script>var myVar = setInterval(setColor, 300);function setColor() {var x = document.body;x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";}function stopColor() {clearInterval(myVar);}</script></body></html>
实例
使用 setInterval() 和 clearInterval() 创建动态进度条:
<!DOCTYPE html><html><style>#myProgress {width: 100%;height: 30px;position: relative;background-color: #ddd;}#myBar {background-color: #4CAF50;width: 10px;height: 30px;position: absolute;}</style><body><div id="myProgress"><div id="myBar"></div></div><br><button onclick="move()">点击这里</button><script>function move() {var elem = document.getElementById("myBar");var width = 0;var id = setInterval(frame, 10);function frame() {if (width == 100) {clearInterval(id);} else {width++;elem.style.width = width + '%';}}}</script></body></html>
相关页面
Window 对象: setInterval() 方法
Window 对象: setTimeout() 方法
Window 对象: clearTimeout() 方法