JavaScript事件队列和setTimeout(...) [英] JavaScript Event Queue and setTimeout(...)
问题描述
这段代码发生了什么
var start = new Date();
setTimeout(function() {
var end = new Date();
console.log('Time elapsed with func1:',end - start, 'ms');
}, 500);
setTimeout(function() {
var end = new Date();
console.log('Time elapsed with func2:',end - start, 'ms');
}, 250);
while (new Date() - start < 1000) {}
日志:
Time elapsed with func2: 1001 ms
Time elapsed with func1: 1017 ms
我预计func1将首先触发,因为它是第一个被添加到事件队列中的事件。然后,由于JS的单线程特性,请等待func1返回,然后执行队列中的下一个事件func2。
那么,发生了什么?
I was expected that func1 will be fire first because it's the first event to be added into the event queue. Then, due to the single thread nature of JS, wait until func1 returns and then executes the next event in the queue which is func2.
So, what's happening?
推荐答案
在计时器到达指定时间时,事件队列没有添加任何内容。
Nothing is added to the event queue UNTIL the timer reaches its appointed time.
所以,事件的顺序如下:
So, the sequence of events is as follows:
- 你注册
func1
计时器为500毫秒。 - 您注册
func2
计时器250毫秒。 - 你在旋转循环时启动
。
- 250ms后,
func2
计时器fires(JS引擎内部)及其回调被添加到事件队列中。 - 500ms后,
func1
计时器触发(内部到JS引擎)并将其回调添加到事件队列中。 - 你的
而
旋转循环终于完成了当前的线程JS完成。 - JS引擎从事件队列中拉出下一个项目,即
func2
回调并执行它。 - 当回调完成执行时,它会从事件队列中拉出下一个项目e
func1
回调并执行它。
- You register the
func1
timer for 500ms. - You register the
func2
timer for 250ms. - You start the
while
spin loop. - After 250ms,
func2
timer fires (internal to the JS engine) and its callback is added to the event queue. - After 500ms,
func1
timer fires (internal to the JS engine) and its callback is added to the event queue. - Your
while
spin loop finally finishes and the current thread of JS finishes. - The JS engine pulls the next item off the event queue which is the
func2
callback and executes it. - When that callback is done executing, it pulls the next item off the event queue which is the
func1
callback and executes it.
因此,你得到输出你看到 func2
回调执行assoon为而
旋转循环完成,然后 func1
回调执行。
And thus, you get the output you see with the func2
callback executing assoon as the while
spin loop is done, then the func1
callback executing.
这篇关于JavaScript事件队列和setTimeout(...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!