如何禁用所有 setTimeout 事件?
我正在使用ajax 和asp.net。我有一个 javascript 函数,它使用 setTimeout 创建许多其他 javascript 函数。发生异步回发后,我想禁用所有这些 setTimeouted 事件。我怎样才能做到这一点?
I am using ajax and asp.net. iI have a javascript function which creates many other javascript functions with setTimeout. After asynchronous postback happenes, I want to disable all of these setTimeouted events. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您无法访问设置计时器的代码,尼克的答案可能不起作用,所以我能想到的就是这个 hack。
这是一个黑客行为,请谨慎使用!
基本上,它会获取最高的计时器 ID 并清除小于该 ID 的所有内容。 但是也可以清除您不想清除的其他计时器!
If you can't get access to the code where the timer is set Nick's answer may not work, so all that I can think of is this hack.
It is a hack, use with caution!
Basically it grabs the highest timer id and clears everything less than that. But it's also possible to clear other timers that you do not want to clear!
当您调用
setTimeout()
时,请存储计时器 ID,以便您可以清除它。如果您要创建许多超时,那么数组是存储 ID 的不错选择。例如:然后,当您想清除它们时:
正如下面指出的 @Robert 所示,
clearTimeout()
如果超时已经发生,则不会抛出错误,因此有这里没有比赛/计时问题。When you call
setTimeout()
, store the timer ID so you can clear it. If you're creating many timeouts, then an array is a good option for storing the IDs. For example:Then when you want to clear them:
As @Robert noted below,
clearTimeout()
won't throw an error if the timeout has already occurred, so there are no race/timing issues here.不确定是否可以在全球范围内执行此操作,但最常见的方法是使用 clearTimeout 。您将 setTimeout() 的返回值传递给clearTimeout(),您可以使用全局变量来存储所有超时变量。
Not sure if you can do this globally, but the most common method is to use clearTimeout. You pass the return value of setTimeout() to clearTimeout(), you could use a global var to store all timeout vars.
首先,我使用了这段代码:
然而,这段代码在 Google Chrome 上不起作用。所以我对此进行了改进:
最后,这是一个黑客,正如上面的评论中提到的,所以请小心使用它。
编辑:修复了循环中使用的错误变量(使用 i 而不是 x)
Firstly, I was using this code:
However, this peace of code did not work on Google Chrome. So I made improvement for this:
Finally, it is a hack, as it was mentioned in the comment above, so use it carefully.
Edit: fixed wrong variable used in loop (use i instead of x)
您可以使用
clearTimeout()
停止另一个函数中一个函数的setTimeout()
you can stop
setTimeout()
of one function in other function usingclearTimeout()