[英]Why does the setTimeout callback wait for the end of the loop when the timer is 0ms?
The thing I don't understand about closures is the fact that the setTimeout
callbacks don't fire until the loop has finished. 对于闭包,我不了解的是
setTimeout
回调在循环完成之前不会触发。 It looks to me that clearly the function is being executed during each iteration. 在我看来,很明显该函数在每次迭代期间都在执行。
I am not concerned why they are all "6"'s I understand that part. 我不担心为什么它们全都是“ 6”,我理解那部分。 I just need an explanation as to why it waits till the loop has to finish before they actually run.
我只需要解释为什么它要等到循环必须完成才能真正运行。
for (var i = 1; i <= 5; i++)
{
setTimeout(function timer()
{
console.log(i);
}, 0);
}
The setTimeouts are queued to start running at the end of the current event loop. setTimeouts排队等待在当前事件循环结束时开始运行。 So, the setTimeouts can fire much later than the end of the for loop.
因此,setTimeouts可以比for循环的末尾触发得多。
MDN has a great description about the event loop with regard to setTimeout: MDN对有关setTimeout的事件循环有很好的描述:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop
Specifically this part: 特别是这部分:
Calling setTimeout will add a message to the queue after the time passed as second argument.
在作为第二个参数传递的时间过去之后,调用setTimeout会将消息添加到队列中。 If there is no other message in the queue, the message is processed right away;
如果队列中没有其他消息,则立即处理该消息;否则,将立即处理该消息。 however, if there are messages, the setTimeout message will have to wait for other messages to be processed.
但是,如果有消息,则setTimeout消息将不得不等待其他消息被处理。 For that reason the second argument indicates a minimum time and not a guaranteed time.
因此,第二个参数表示最短时间而不是保证时间。
JavaScript runs with a single event loop . JavaScript使用单个事件循环运行。
The event loop is busy running the function that is calling setTimeout
so it isn't looking to see if any events are on the timeout queue waiting to run. 事件循环正在忙于运行正在调用
setTimeout
的函数,因此它不希望查看是否有任何事件在等待运行的超时队列中。
Even if that wasn't the case, most JS implementations implement a minimum timeout (see Minimum delay and timeout nesting ) value and raise whatever you pass ( 0
) to it if it falls below that value. 即使不是这种情况,大多数JS实现也会实现最小超时值(请参见最小延迟和超时嵌套 ),并在该值低于该值时提高传递给它的值(
0
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.