setTimeout无法在无限循环内工作 [英] setTimeout not working inside infinite loop
问题描述
while(true){
window.setTimeout(function(){
myMethod()
},15000);
}
函数myMethod(){
alert(repeat);
}
上面的一段代码是为了无限地执行mymethod而写的,我运行代码我的浏览器挂起,重复弹出不断生成,但这里的时间是15秒。我想避免setInterval,所以使用这种技术来达到我的目的。
解决方案 Javascript是单线程的(除了Web工作者,但这对这个例子来说是不重要的,所以我们会忽略它)。这意味着setTimeout实际上做的是安排一些代码在未来至少一段时间之后被执行,但是只有当浏览器停止了当时在渲染线程上执行的任何其他操作时,可以渲染html,或执行javascript。因此,直到while循环(以及任何代码包含它)完成并将控制权返回给浏览器时,setTimeout中的代码才能执行。但是它是一个无限循环,所以控制永远不会返回到浏览器,setTimeout中的代码永远不会执行。事实上,javascript中常见的习惯用法是使用一个超时时间为0(或可能为1)的setTimeout,以便在当前事件的代码执行后尽快执行一些代码,并且通常在浏览器呈现由javascript所做的任何html更改之后。
我不知道你的确切用例是什么,但是你可以使用setInterval(它就像setTimeout,但是在间隔),或者通过在setTimeout函数内调用setTimeout来实现递归的无限循环,但让浏览器在迭代之间执行其他任务。
while(true){
window.setTimeout(function() {
myMethod()
}, 15000);
}
function myMethod() {
alert("repeat");
}
Above piece of code is written to execute mymethod infinitely but in certain intervals but once I run the code my browser hangs and the repeat pop up generates constantly but the time here is 15 secs. I wanted to avoid setInterval so using this technique for my purpose.
Javascript is single threaded (with the exception of web workers, but that is irrelavent to this example so we will ignore it). What this means is that setTimeout actually does is schedules some code to be executed some time in the future, after at least some amount of time, but only when the browser has stopped whatever else it was doing on the rendering thread at the time, which could be rendering html, or executing javascript.
So, the code in the setTimeout can't execute until the while loop (and whatever code contains it) finishes and returns control back to the browser. But it is an infinitely loop, so control is never returned to the browser and the code in the setTimeout is never executed.
In fact, a common idiom in javascript is to use a setTimeout with a timeout of 0 (or possibly 1) so that some code will be executed as soon as possible after the code for the current event has executed, and typically after the browser has rendered any html changes that were made by javascript.
I don't know what your exact use case is, but you can probably do what you want either using a setInterval (which is like setTimeout but is called repeatedly at an interval), or by calling setTimeout inside the function in the setTimeout to achieve an infinite loop with recursion, but letting the browser perform other tasks in between iterations.
这篇关于setTimeout无法在无限循环内工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!