取消设置为ID的多个超时 [英] Cancel multiple timeouts set to an ID

查看:93
本文介绍了取消设置为ID的多个超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太确定这个问题的机制,但是我试图将一个setTimeout设置为一个变量ID,我可以使用clearTimeout轻松取消它。但是,如果setTimeout在clearTimeout之前被触发两次,那就很糟糕。



示例:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_settimeout2



单击Try It两次然后Stop the Alert两次,仍然会调用set timeout的功能。同样,我不确定为什么尝试它会触发该函数两次,因为事件被保存到一个被覆盖的变量。



知道这里发生了什么?

解决方案

就像MCL解释的那样,你将失去对先前超时的引用,因为新的赋值会覆盖它。 / p>

你可以做的是把超时放到一个数组:

  var myTimer = []; 

函数myFunction(){
myTimer.push(setTimeout(function(){alert(Hello)},3000));
}

函数myStopFunction(){
clearTimeout(myTimer.pop());
}

这样你就可以在点击停止提醒按钮。



jsFiddle


I'm not quite sure of the mechanics of this problem, but I'm trying to have a single setTimeout set to a variable ID that I can easily cancel using clearTimeout. But, if setTimeout gets triggered twice before clearTimeout, things go wacky.

Example: http://www.w3schools.com/js/tryit.asp?filename=tryjs_settimeout2

Clicking "Try It" twice and then "Stop the Alert" twice, the function of set timeout still gets called. Likewise, I'm not sure why Try It would trigger the function twice considering the event is saved to a variable that is getting overwritten.

Any idea of what's going on here?

解决方案

Like MCL has explained, you're loosing the reference to previous timeout, since a new assignment will override it.

What you can do is to put the timeouts to an array:

var myTimer = [];

function myFunction () {
    myTimer.push(setTimeout(function(){alert("Hello")},3000));
}

function myStopFunction () {
    clearTimeout(myTimer.pop());
}

This way you can cancel the last set timeout when clicking Stop the alert button.

A live demo at jsFiddle.

这篇关于取消设置为ID的多个超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆