Node.js version 0.10 was released today and introduced setImmediate
. The API changes documentation suggests using it when doing recursive nextTick
calls.
From what MDN says it seems very similar to process.nextTick
.
When should I use nextTick
and when should I use setImmediate
?
The setImmediate function is used to execute a function right after the current event loop finishes. In simple terms, the function functionToExecute is called after all the statements in the script are executed. It is the same as calling the setTimeout function with zero delays.
Use nextTick() when you want to make sure that in the next event loop iteration that code is already executed.
setImmediate() vs setTimeout()setImmediate() is designed to execute a script once the current poll phase completes. setTimeout() schedules a script to be run after a minimum threshold in ms has elapsed.
setImmediate() vs setTimeout()setImmediate() is designed to execute a script once the current Poll phase completes. Execution of this callback takes place in Check phase (5). setTimeout() schedules a callback function to be run after a minimum threshold in ms has elapsed.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With