如何停止 setInterval 和 setTimeout 事件

前端APP 投稿 9200 0 评论

如何停止 setInterval 和 setTimeout 事件

js 代码中执行循环事件时,经常会用到 setInterval 和 setTimeout 这两个方法,关于这两个方法的细节这里不详细讨论了,简要分享下在需要停止循环事件的时候该如何操作。

(1)setInterval 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式,停止该方法可使用 clearInterval 方法。具体示例如下:


<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<body>
<input type="text" id="clock" size="50" />
<script language=javascript>
var int=self.setInterval("clock(",50;//每隔 50 毫秒调用 clock( 函数
function clock({
	var t=new Date(;
	document.getElementById("clock".value=t;
}
</script>
<button onclick="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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var c=0;
var t;
function timedCount({
	document.getElementById('txt'.value=c;
	c=c+1;
	t=setTimeout("timedCount(",1000;
}
function stopCount({
	clearTimeout(t;
}
</script>
</head>
<body>
<input type="button" value="开始计数" onClick="timedCount(">
<input type="text" id="txt">
<input type="button" value="停止计数" onClick="stopCount(">
</body>
</html>

clearTimeout( 方法可取消由 setTimeout( 方法设置的 timeout。

语法 clearTimeout(id_of_settimeout

参数 id_of_setinterval 表示由 setTimeout( 返回的 ID 值。该值标识要取消的延迟执行代码块。

编程笔记 » 如何停止 setInterval 和 setTimeout 事件

赞同 (41) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽