setImmediate vs. nextTick

2022-01-30 00:00:00 node.js javascript setimmediate

Node.js 0.10 版今天发布,引入了setImmediate.API 更改 文档建议在进行递归 nextTick 调用时使用它.

Node.js version 0.10 was released today and introduced setImmediate. The API changes documentation suggests using it when doing recursive nextTick calls.

从 MDN 所说的看来非常相似到 process.nextTick.

From what MDN says it seems very similar to process.nextTick.

什么时候应该使用nextTick,什么时候应该使用setImmediate?

When should I use nextTick and when should I use setImmediate?

推荐答案

如果您想在事件队列中已经存在的任何 I/O 事件回调之后排队函数,请使用 setImmediate.使用 process.nextTick 将函数有效地排在事件队列的头部,以便在当前函数完成后立即执行.

Use setImmediate if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.

因此,如果您尝试使用递归分解长期运行的、受 CPU 限制的作业,您现在需要使用 setImmediate 而不是 process.nextTick 将下一次迭代排队,否则任何 I/O 事件回调都没有机会在迭代之间运行.

So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate rather than process.nextTick to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.

相关文章