How process.nextTick() works in Node.js?
Aman Mittal
254

There are there types of callback queues. (idle observer, I/O observer, check observer, ordered in priority). All callbacks in idle observers will always run before I/O/check observers. In this case, process.nextTick() belongs to idle observer, and setTimeout belongs to check observer, so nextTick will always run before setTimeout.

nextTick will NOT add the callback in the front of queue, but in the end of idle observer queue (still ahead of all setTimeout callbacks though)

Example:

process.nextTick(() => {
console.log("tick 1");
process.nextTick(() => {
console.log("tick 2");
process.nextTick(() => {
console.log("tick 3");
});
});
process.nextTick(() => {
console.log("tick 4");
process.nextTick(() => {
console.log("tick 5");
});
});
});
setTimeout(() => {
console.log("timeout");
});
setImmediate(() => {
console.log("immediate");
});

Output:

tick 1
tick 2
tick 4
tick 3
tick 5
timeout
immediate
Show your support

Clapping shows how much you appreciated Melvin Tu’s story.