且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript事件队列和setTimeout(...)

更新时间:2022-04-06 09:28:49

在计时器到达指定时间时,事件队列没有添加任何内容。

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.