JavaScript中停止执行setInterval和setTimeout事件的方法
js代码中执行循环事件时,经常会用到setInterval和setTimeout这两个方法,关于这两个方法的细节这里不详细讨论了,简要分享下在需要停止循环事件的时候该如何操作。
(1)setInterval方法可按照指定的周期(以毫秒计)来调用函数或计算表达式,停止该方法可使用clearInterval方法。具体示例如下:
<html>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<body>
<inputtype="text"id="clock"size="50"/>
<scriptlanguage=javascript>
varint=self.setInterval("clock()",50);//每隔50毫秒调用clock()函数
functionclock(){
vart=newDate();
document.getElementById("clock").value=t;
}
</script>
<buttononclick="window.clearInterval(int)">停止interval</button>
</body>
</html>
语法clearInterval(id_of_setinterval)
参数id_of_setinterval表示由setInterval()返回的ID值。
clearInterval()方法可取消由setInterval()设置的timeout;clearInterval()方法的参数必须是由setInterval()返回的ID值。
(2)setTimeout方法用于在指定的毫秒数后调用函数或计算表达式。停止该方法可使用clearTimeout方法。具体示例如下:
提示:setTimeout()只执行code一次。如果要多次调用,请使用setInterval()或者让code自身再次调用setTimeout()。
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<scripttype="text/javascript">
varc=0;
vart;
functiontimedCount(){
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}
functionstopCount(){
clearTimeout(t);
}
</script>
</head>
<body>
<inputtype="button"value="开始计数"onClick="timedCount()">
<inputtype="text"id="txt">
<inputtype="button"value="停止计数"onClick="stopCount()">
</body>
</html>
clearTimeout()方法可取消由setTimeout()方法设置的timeout。
语法clearTimeout(id_of_settimeout)
参数id_of_setinterval表示由setTimeout()返回的ID值。该值标识要取消的延迟执行代码块。