node 文档找提到 setTimeout/setImmediate 返回结果的顺序不一定。 那么两种可能性的分别是怎样的?

参考链接

---- 更新一下问题。

那么这种两种可能性分别在什么情况下才会发生?

我看了一下阮老师的文章,对于这个问题又有了一些的新的理解:

clipboard.png

  1. 在主进程中, setTimeout 和 setImmediate 执行的先后问题,
clipboard.png
确实,存在一个默认最小间隔为1ms的问题,那么如果 setImmediate 能够在1ms来被触发,就会比 setTimeout 快。
  1. 为什么在 i/o cycle 中, setImmediate 一定比 setTimeout 快?

因为在执行 i/o cycle 过程中, 进入了 poll phase,执行其 回调函数中的代码,分别遇到了 setTimeout 和 setImmediate。此时的 poll phase 的队列尚为被清空,还有一个函数在里面(执行中)。当这个函数结束的时候,整个event loop 中刚刚通过 setImmediate 注册了一个回调,所以就会继续到 check phase。 这也是为什么
Timers phase 在 check phase 前面,但是 setImmediate 却在一定会在 setTimeout 前面执行(同一i/o cycle 时)。

当然以上是我个人的理解。

在看了 @改名字很伤神 推荐的 nodejs中的event loop 后,觉得自己的基础功还是不扎实,没有办法更加深入的去理解问题,汗颜。

同时,欢迎大家就我的看法做指正。

阅读 2.3k
3 个回答
setTimeout/setImmediate 返回结果的顺序不一定。 那么两种可能性的分别是怎样的?

那当然,你都没法保证是不是同一次轮询(你可能是问这个?)。这就是为什么后面要加fs.readFile

文檔寫得很明白,當setTimeout() 和 setImmediate() 都不在I/O cycle (讀寫周期)內,它們的執行順序會受到程序的性能影響而變得不確定。

For example, if we run the following script which is not within an I/O
cycle (i.e. the main module), the order in which the two timers are
executed is non-deterministic, as it is bound by the performance of
the process.

但是,如個它們都在I/O cycle內,則不管有多少個setTimeout(),setImmediate()永遠先執行,這同時是setImmediate()的優勢。

The main advantage to using setImmediate() over setTimeout() is
setImmediate() will always be executed before any timers if scheduled
within an I/O cycle, independently of how many timers are present.

参考链接

我自己也来回答一下,虽然是我自己问的。

这个问题放在node下面来看的话,可以这么理解,

setTimeout 和 setImmediate 这两个函数不存在谁前谁后的关系,只不过在 node 的 event loop 下,

两者分属不同的阶段(phase):

setTimeout -> timer

setImmediate -> check

这两个阶段在同一个 Loop 中确实有先后关系,但是如果是多个 Loop 则不存在先后关系。

推荐问题