Node provides us the setTimeout
, setImmediate
and Process.nextTick
constructs, but do you know when to use what ?
To answer that, we need to understand the sequence of Node's event loop. Each stage in a run of event loop is called Phase
. Each of the phases are then executed in a certain order.
These phases are
-
Timers - This phase executes the
setTimeout
andsetInterval
callbacks. - Pending callbacks - I/O callbacks that have been deferred to this loop run from the last loop run.
- Poll - Looks for new I/O events to be executed. Also executes the callbacks for completed operations.
-
Check - Executes the
setImmediate
callbacks immediately after the poll phase. Important thing to note is - when the check phase has asetImmediate
to be executed and poll phase is idle, the event loop immediately jumps to check phase without waiting for new I/O events to arrive.
Hence, it is fair to assume that setImmediate()
will always execute before setTimeout()
. There is a catch here however as demonstrated by below example
setTimeout(() => {
console.log('Hello')
}, 0)
setImmediate(() => {
console.log('World')
})
//Output
Hello
World
When the setTimeout
is passed a value 0, the order in which these two timers are executed is not guaranteed to be in sequence. Reason being a setTimeout
with 0ms wait is immediately queued as an I/O event in poll phase, so poll phase might choose to execute setTimeout
or move on to setImmediate
in check phase if poll phase execution time is exhausted.
But when these two functions are included in a callback of a function, then the setImmediate
is always executed first because the setTimeout
is queued to be executed after the callback is returned.
What does Process.nextTick
do ?
The core concept to understand the functioning of Process.nextTick
is the Phase of event loop. As the name suggests, Process.nextTick
executes the code passed to it before the start of next phase.
Process.nextTick is very useful when you want the code to finish executing before the callback is executed or handle the errors that are important.
Eg: Consider you are making multiple API calls and the response of the API 'A' is very important for you to check for the user login session. You want to parse this response before other responses so as to decide the user experience.
What you would do here is place the callback code of API 'A' in a Process.nextTick
, so as soon as the API responds , the code is executed and user can handle that error immediately in same phase before event loop goes to execute the other callbacks.
Just to show the comparison between setTimeout()
vs setImmediate()
vs Process.nextTick
setTimeout(() => {
console.log('Hello')
}, 0)
setImmediate(() => {
console.log('World')
})
Process.nextTick(() => {
console.log('Dev.to')
})
//output
Dev.to
Hello
World
Top comments (0)