在 Javascript 中停止嵌套超时 [英] Stopping Nested Timeouts in Javascript
问题描述
我想执行一段任意代码,并且可以随时停止它.我想我可以用 setTimeout
做到这一点,然后用 clearTimeout
来阻止它.但是,如果超时中的代码创建了自己的超时,那么即使我清除了原始超时,这些代码也会继续执行.
I want to execute a piece of arbitrary code and be able to stop it whenever I want. I figured I could do this with setTimeout
and then use clearTimeout
to stop it. However if the code in the timeout creates it's own timeouts, then those keep executing even after I clear the original.
示例:
var timeoutID = setTimeout(
function(){
console.log("first event can be stopped with clearTimout(timeoutID)");
setTimeout(function(){console.log("but not this one")}, 5000)
}, 5000)
现在一种方法是控制正在执行的代码,并使其将任何额外超时的值存储到全局变量中并立即清除它们.但是有没有更好的方法来做到这一点?有没有办法在任意代码上做到这一点?
Now one way would be to control the code being executed and make it store the value of any additional timeouts into a global variable and clear them all at once. But is there a better way to do this? And is there a way to do this on arbitrary code?
澄清一下,我试图能够执行我想要的任何函数,然后在我想要的时候停止它,即使该函数包含超时
To clarify, I'm trying to be able to execute any function I want, then stop it whenever I want, even if the function contains timeouts
推荐答案
您也可以将内部超时设置为变量:
You can put the inner timeout into a variable too:
var innerTimeout,
timeoutID = setTimeout(
function(){
console.log("first event can be stopped with clearTimout(timeoutID)");
innerTimeout = setTimeout(function(){console.log("but not this one")}, 5000);
}, 5000);
这篇关于在 Javascript 中停止嵌套超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!