首页IT科技怎么清除定时器(如何清除全部的定时器)

怎么清除定时器(如何清除全部的定时器)

时间2025-05-01 22:28:15分类IT科技浏览6990
导读:通过 setTimeout( 函数来建立定时器,并通过...

通过 setTimeout() 函数来建立定时器              ,并通过 clearTimeout() 函数来清除定时器              。

let timerTimeout = setTimeout(() => { console.log("2222222-----------------------------"); }, 1000); clearTimeout(timerTimeout);

通过 setInterval() 函数来建立定时器                      ,并通过 clearInterval() 函数来清除定时器                      。

let timerInterval = setInterval(() => { console.log("11111111-----------------------------"); }, 2000); clearInterval(timerInterval);

当我们给定时器赋值给一个变量的时候       ,可以通过 clearTimeout 和 clearInterval 来清除指定的定时器       。我们如何来清除全部的定时器呢?

我们来看一段代码:

let timerTimeout = setTimeout(() => {

console.log(“2222222-----------------------------              ”);

}, 1000);

console.log(“timerTimeout-----------------------------                      ”, timerTimeout); let timerInterval = setInterval(() => { console.log("11111111-----------------------------"); }, 2000); console.log("timerInterval-----------------------------", timerInterval); let timer3 = setTimeout(() => { console.log("333333-----------------------------"); }, 1000); console.log(timer3-----------------------------, timer3) let timer4 = setInterval(() => { console.log("44444444-----------------------------"); }, 1000);

通过打印 **timerTimeout ** 和 **timerInterval ** 的值              ,我们可以知道                      ,每个定时器会返回一个number类型的ID值       ,并且会从1开始逐渐递增              。setTimeout() 和 **setInterval()**共用一个ID       ,每有一个 setTimeout()setInterval() 函数                      ,ID值就会增加1                      。

通过以上的特性可知               ,当我们新建一个定时器的时候       ,这个定时器的 ID 的值是最大的                     ,通过遍历所有的ID值               ,分别清除对应的定时器,即可清除全部的定时器       。

let endTimer = setTimeout(() => {}, 100000); for (let i = 0; i <= endTimer; i++) { // 清除setInterval创建的定时器 clearInterval(i) // 清除setTimeout创建的定时器 clearTimeout(i) }

for 循环中调用 clearIntervalclearTimeout 是利用了这两个函数                     ,当传入的值没有对应的定时器时                      ,不会抛出错误的特性       。这样不管ID值所对应的是 setInterval 创建的定时器还是 setTimeout 创建的定时器,或者没有定时器              ,都可以正确清除                      ,并且不会抛出错误                      。

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
魂斗罗python源代码(学习 Python 之 Pygame 开发魂斗罗(四)) js入门教程视频(JS入门到精通完整版)