Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setImmediate vs. nextTick

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?

like image 468
Benjamin Gruenbaum Avatar asked Mar 11 '13 22:03

Benjamin Gruenbaum


People also ask

What is the use of 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.

When should I use nextTick?

Use nextTick() when you want to make sure that in the next event loop iteration that code is already executed.

What is the difference between setImmediate () and setTimeout ()?

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.

What is difference between setImmediate and setImmediate <UNK> setTimeout 0?

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.


1 Answers

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.

like image 149
JohnnyHK Avatar answered Oct 20 '22 17:10

JohnnyHK