Difference between process.nextTick() and setImmediate() Methods
To understand the difference between process.nextTick() and setImmediate() methods, we first need to understand the working of Node.js Event Loop.
What is Node.js Event Loop?
Working of Event Loop?
timers–>pending callbacks–>idle,prepare–>connections(poll,data,etc)–>check–>close callbacks
Understanding process.nextTick() method: Whenever a new queue of operations is initialized we can think of it as a new tick. The process.nextTick() method adds the callback function to the start of the next event queue. It is to be noted that, at the start of the program process.nextTick() method is called for the first time before the event loop is processed.
Understanding setImmdeiate() method: Whenever we call setImmediate() method, it’s callback function is placed in the check phase of the next event queue. There is slight detail to be noted here that setImmediate() method is called in the poll phase and it’s callback functions are invoked in the check phase.
For the above program, event queues are initialized in the following manner:
- In the first event queue only ‘program started is printed’.
- Then second event queue is started and function C i.e. callback of process.nextTick() method is placed at the start of the event queue. C is executed and the queue ends.
- Then previous event queue ends and third event queue is initialized with callback D. Then callback function A of setImmdeiate() method is placed in the followed by B.
Now, the third event queue looks like this,
D A B
Now functions D, A, B are executed in the order they are present in the queue.
Let us see the differences in a tabular form -:
|1.||process.nextTick() is used to schedule a callback function to be invoked in the next iteration of the Event Loop.||setImmediate() method is used to execute a function right after the current event loop finishes.|
|2.||Its benefit is that it has no time bound to take a callback.||setImmediate() method is only processed on the check handler phase of the event loop|
|3.||process.nextTick() function is specific to the Node.js Event Loop||It is generally found in the Timers module|
Its syntax is -:
Its syntax is -:
|5.||It has a benefit that it has the potential to cause I/O starvation||Its return value is a unique timer identifier that can be used in another function call.|