javascript 没有延迟的 setTimeout 是否与立即执行函数相同?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3580068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is setTimeout with no delay the same as executing the function instantly?
提问by Aishwar
I am looking at some existing code in a web application. I saw this:
我正在查看 Web 应用程序中的一些现有代码。我看到了这个:
window.setTimeout(function () { ... })
window.setTimeout(function () { ... })
Is this the same as just executing the function content right away?
这和直接执行函数内容一样吗?
回答by angusC
It won't necessarily run right away, neither will explicitly setting the delay to 0. The reason is that setTimeout removes the function from the execution queue and it will only be invoked after JavaScript has finished with the current execution queue.
它不一定会立即运行,也不会明确地将延迟设置为 0。原因是 setTimeout 从执行队列中删除该函数,并且只有在 JavaScript 完成当前执行队列后才会调用它。
console.log(1);
setTimeout(function() {console.log(2)});
console.log(3);
console.log(4);
console.log(5);
//console logs 1,3,4,5,2
for more details see http://javascriptweblog.wordpress.com/2010/06/28/understanding-javascript-timers/
有关更多详细信息,请参阅http://javascriptweblog.wordpress.com/2010/06/28/understanding-javascript-timers/
回答by Daniel Vandersluis
There is a minimum delay that setTimeoutuses (4ms as per HTML5, Firefox 3.6 uses 10ms). There is a discussion about it on the Mozilla Developer Center documentation page.
有setTimeout使用的最小延迟(根据 HTML5 为 4 毫秒,Firefox 3.6 使用 10 毫秒)。Mozilla 开发人员中心文档页面上有关于它的讨论。
回答by Gary
You are missing the millisecond parameter...
您缺少毫秒参数...
setTimeout(function() { /*something*/ }, 0);
The 0 sets the delay to 0 but what it actually does is to let your function "jump the queue"of the browser execution list. The browser has a bunch of things to do such as rendering objects on the page, and by calling this, your function will run as soon as the browser has some cycles.
0 将延迟设置为 0,但它实际所做的是让您的函数“跳入浏览器执行列表的队列”。浏览器有很多事情要做,比如在页面上渲染对象,通过调用它,你的函数会在浏览器有一些周期时运行。

