JavaScript事件队列和setTimeout(...) [英] JavaScript Event Queue and setTimeout(...)

查看:65
本文介绍了JavaScript事件队列和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:


  1. 你注册 func1 计时器为500毫秒。

  2. 您注册 func2 计时器250毫秒。

  3. 你在旋转循环时启动

  4. 250ms后, func2 计时器fires(JS引擎内部)及其回调被添加到事件队列中。

  5. 500ms后, func1 计时器触发(内部到JS引擎)并将其回调添加到事件队列中。

  6. 你的旋转循环终于完成了当前的线程JS完成。

  7. JS引擎从事件队列中拉出下一个项目,即 func2 回调并执行它。

  8. 当回调完成执行时,它会从事件队列中拉出下一个项目e func1 回调并执行它。

  1. You register the func1 timer for 500ms.
  2. You register the func2 timer for 250ms.
  3. You start the while spin loop.
  4. After 250ms, func2 timer fires (internal to the JS engine) and its callback is added to the event queue.
  5. After 500ms, func1 timer fires (internal to the JS engine) and its callback is added to the event queue.
  6. Your while spin loop finally finishes and the current thread of JS finishes.
  7. The JS engine pulls the next item off the event queue which is the func2 callback and executes it.
  8. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆