setImmediate setTimeout nextTick
发布于 1年前 作者 mikemoto 727 次浏览

v0.10.21官方文档这样描述:

To schedule the “immediate” execution of callback after I/O events callbacks and before setTimeout and setInterval . Returns an immediateId for possible use with clearImmediate(). Optionally you can also pass arguments to the callback.

Immediates are queued in the order created, and are popped off the queue once per loop iteration. This is different from process.nextTick which will execute process.maxTickDepth queued callbacks per iteration. setImmediate will yield to the event loop after firing a queued callback to make sure I/O is not being starved. While order is preserved for execution, other I/O events may fire between any two scheduled immediate callbacks.

按照道理来说,nextTick运行最快,然后到setImmediate,最后到setTimeout 。

但是从我多次运行的结果来看,事实并不是这样。nextTick最快没问题,但是每次都是setTimeout 先出现,然后setImmediate才出现。

这是为什么呢?求解答。。。

3 回复

先理解event loop

setTimeout和setImmediate顺序是随机的,不是你说的一定是setTimeout的回调先执行,当然我假设你说的是延时入队是设置为0

To schedule the “immediate” execution of callback after I/O events callbacks and before setTimeout and setInterval . 这是官网原话啊。就是上面第一句话 按照官网说的,不是应该setImmediate一定比setTimeout快?

回到顶部