In the previous article, we learned about the six phases of the event loop, their functions, and which types of callback functions are handled in each. Additionally, there is a special phase called process.nextTick, which is not part of the Event loop but has the highest priority.
This seemingly simple concept often confuses many, even experienced developers. So, when process.nextTick, setImmediate, and setTimeout are placed together, which callback do you think executes first?
First, letβs revisit the six-phase model of the event loop.
βββββββββββββββββββββββββββββ
ββ>β timers β
β βββββββββββββββ¬ββββββββββββββ
β βββββββββββββββ΄ββββββββββββββ
β β pending callbacks β
β βββββββββββββββ¬ββββββββββββββ
β βββββββββββββββ΄ββββββββββββββ
β β idle, prepare β
β βββββββββββββββ¬ββββββββββββββ
β βββββββββββββββ΄ββββββββββββββ
β β poll β
β βββββββββββββββ¬ββββββββββββββ
β βββββββββββββββ΄ββββββββββββββ
β β check β
β βββββββββββββββ¬ββββββββββββββ
β βββββββββββββββ΄ββββββββββββββ
ββββ€ close callbacks β
βββββββββββββββββββββββββββββ
Each phase handles specific types of events. We cannot flood the Event loop with events and expect it to process them sequentially; certain events need to be processed before others. Dividing into phases ensures this.
In every loop iteration, Node.js traverses each phase, processing the events in that phase before moving to the next. Here, setTimeout is processed in "timers," located at the top of the Event loop. Meanwhile, setImmediate is processed in "check." Does this mean that a setTimeout with a delay of 0 always executes before setImmediate?
In a synchronous program, meaning no asynchronous functions are called, if you use setTimeout(fn, 0), the callback is scheduled in the "timers" phase. If you use setImmediate(), the callback is scheduled in the "check" phase. Theoretically, the callback of setTimeout should always execute before setImmediate.
setTimeout(() => {
console.log('setTimeout');
}, 0);
setImmediate(() => {
console.log('setImmediate');
});
When running the above code, youβll notice "setTimeout" and "setImmediate" appear in no particular orderβsometimes "setTimeout" logs first, other times "setImmediate" does. This inconsistency is because, at the start of a program, Node.js experiences an initial delay before stabilizingβit might begin in the "timers" phase or the "check" phase.
In cases where the program calls an asynchronous function, the execution order differs, with setImmediate always taking precedence because it is executed immediately after the I/O operation completes, as it resides in the "check" phase of the event loop, which occurs right after the "poll" phase (where I/O tasks are processed).
setTimeout(fn, 0) only executes after the event loop cycles back to the "timers" phase, meaning it has to wait for another loop iteration to reach "timers."
fs.readFile("README.md", () => {
setTimeout(() => {
console.log('setTimeout');
}, 0);
setImmediate(() => {
console.log('setImmediate');
});
});
Therefore, we should use setImmediate to run a callback immediately after an I/O task completes.
setImmediate proves useful for logging requests. For example, in an HTTP server:
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello World\n");
// log to a file (less critical task)
setImmediate(() => {
fs.appendFile("server.log", `Request: ${req.url}\n`, (err) => {
if (err) throw err;
console.log("Logged request to server.log");
});
});
Many might think setImmediate is unnecessary here, as fs.appendFile is an asynchronous function and does not affect the current response time. Thus, removing setImmediate could avoid redundant code.
Thatβs not necessarily correct. In reality, servers often handle numerous simultaneous requests. Using setImmediate pushes the logging task into the "check" phase, leaving time for the "poll" phaseβwhich handles critical task callbacksβthereby improving server performance. Always remember to push less critical tasks to the "check" phase, prioritizing the "poll" phase.
Additionally, setImmediate can reduce the main threadβs load. For more details, refer to the article Two Techniques to Prevent the Event Loop from Being Blocked by CPU-Intensive Tasks. That article discusses a "Partitioning" technique using setImmediate to prevent the Event loop from stalling when processing large amounts of data.
Looking back at the six phases of the Event loop, you wonβt find any phase handling process.nextTick callbacks. This is because process.nextTick is a special phase where its callback is always processed at the beginning of every phase of the event loop.
For instance, after the Event loop finishes processing "timers" callbacks and is about to move to "pending callbacks," it pauses to process process.nextTick callbacks. Once completed, it transitions to "pending callbacks" and so on in subsequent phases. This means process.nextTick has very high priority in the Event loop.
How should we use process.nextTick? The answer is straightforward: whenever you need to perform a task with the highest priority before other phases are processed to ensure immediate execution.
For example, process.nextTick is often applied in "Partitioning" techniques similar to setImmediate, except that each loop processes setImmediate once, whereas process.nextTick can be processed up to six times per loop.
For this reason, libraries like bcrypt, used for hashingβa computationally heavy task with the potential to block the Event loopβextensively apply process.nextTick to prevent such behavior.
In this article, we deeply explored how process.nextTick, setImmediate, and setTimeout operate in Node.js, clarifying their roles in the Event loop. process.nextTick stands out with the highest priority, executing right before transitioning to other Event loop phases, making it an ideal choice for tasks requiring immediate execution. Meanwhile, setImmediate is preferred for handling less critical tasks after completing I/O, reducing the Event loopβs load and optimizing system performance. setTimeout is typically used to schedule execution in subsequent loops but is susceptible to Node.jsβs initial delay.
Understanding these differences not only helps developers use callbacks more effectively but also optimizes application performance, especially in multitasking systems with high concurrency demands. Depending on the scenario, choosing the right tool among process.nextTick, setImmediate, and setTimeout can significantly impact how your application performs and responds. Use them wisely to ensure tasks are processed in the correct priority and align with system requirements.