简体   繁体   English

如何强制清除Javascript中的间隔

[英]how to force to clear interval in Javascript

All: 所有:

I wonder if there is a way that I can force to clear all the interval counters, for example: 我想知道是否有一种方法可以强制清除所有间隔计数器,例如:

/* var counter = */ setInterval(function(){console.log("Tick")}, 1000)

But I forget to get the reference ( that counter variable, which is a number if printed out in console), I wonder if there is a way I can find what number that Interval is, so I can call clearInterval 但是我忘了获得引用(该counter变量,如果在控制台中打印出来则为数字),我想知道是否有一种方法可以找到Interval是什么数字,因此可以调用clearInterval

The only thing you can be sure about the id is that is will be an integer greater than zero. 您唯一可以确定的ID是整数,该整数将大于零。 See the spec . 参见规格

let handle be a user-agent-defined integer that is greater than zero that will identify the timeout to be set by this call in the list of active timers. 让handle为大于零的用户代理定义的整数,它将标识活动计时器列表中此调用要设置的超时。

So you can, very inefficiently, try them all: 因此,您可以非常低效地尝试所有方法:

for (let i = 1; i < Number.MAX_SAFE_INTEGER; i++) {
    clearInterval(i);
}

Note that this will take a while (that's a lot of numbers to loop over, although you might assume that the browser will issue them in sequential order and you'll never generate more than a certain number). 请注意,这将需要一段时间(有很多数字需要循环,尽管您可能会假设浏览器将按顺序发布它们,并且您生成的数字永远不会超过一定数量)。

Note also that ( See MDN ): 另请注意( 请参阅MDN ):

the pool of IDs used by setInterval() and setTimeout() are shared, which means you can technically use clearInterval() and clearTimeout() interchangeably setInterval()和setTimeout()使用的ID池是共享的,这意味着您可以在技术上互换使用clearInterval()和clearTimeout()

So this will blat all setTimeout calls as well as all setInterval calls. 因此,这将对所有setTimeout调用以及所有setInterval调用进行setInterval

Another option, one that I don't like, is to monkey patch setInterval . 我不喜欢的另一种选择是猴子修补setInterval Basically, decorate it in a way to store a reference of setInterval somewhere else. 基本上,装饰它的方式是将setInterval的引用存储在其他位置。

allIntervals = []
originalSetInterval = window.setInterval
window.setInterval = (...args) => {
    const interval = originalSetInterval(...args)
    allIntervals.push(interval)
    return interval
}

// ...
setInterval(function(){console.log("Tick")}, 1000)
setInterval(function(){console.log("Tick 2")}, 1000)

Then it's just a matter of calling all of them to clear them 然后,只需召集所有人清除它们即可

allIntervals.map(window.clearInterval)

You may want to override window.clearInterval as well, and pop the right value from allIntervals . 您可能还想覆盖window.clearInterval ,然后从allIntervals弹出正确的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM