JavaScript中停止setInterval和setTimeout定时器的方法

作者:青柠

时间:2026-10-29

浏览:276

本文介绍如何在JavaScript中停止循环执行的setInterval和一次性执行的setTimeout。通过保存定时器返回的ID,分别使用clearInterval和clearTimeout方法即可取消定时任务。文章提供了完整的HTML示例代码,演示了如何创建和停止时钟显示及计数功能。

文章目录

在JavaScript代码中处理循环事件时,开发者通常会使用setInterval和setTimeout这两个核心方法。本文将简要探讨在需要终止这些循环事件时,具体应该采取哪些操作手段。

停止setInterval定时器的方法

首先来看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方法的语法为:clearInterval(id_of_setinterval)。

其中,参数id_of_setinterval代表由setInterval()方法返回的ID值。

clearInterval()方法的作用是取消由setInterval()设置的timeout;该方法的参数必须是由setInterval()返回的ID值。

停止setTimeout定时器的方法

其次,setTimeout方法用于在指定的毫秒数之后调用函数或执行计算表达式。若要停止该方法,可以使用clearTimeout方法。具体示例如下:

提示:setTimeout()仅执行代码一次。如果需要多次调用,请使用setInterval(),或者让代码自身再次调用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方法的语法为:clearTimeout(id_of_settimeout)。

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

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章