Middle+
What is the structure of the event loop in Node.js?
sobes.tech AI
Answer from AI
The event loop in Node.js consists of several phases:
- Timers: Executes callbacks from
setTimeout()andsetInterval(). - Pending Callbacks: Executes callbacks from certain system operations, such as TCP socket errors.
- Poll:
- Checks for new I/O events (files, sockets, etc.).
- Executes callbacks for these events (except those deferred to
setImmediate()). - If there are timers with zero delay (
setImmediate()), it transitions to thecheckphase. - If there are no I/O events to process and the script is not waiting for other operations, it may wait for new events.
- Check: Executes callbacks from
setImmediate(). - Close Callbacks: Executes callbacks for close events, such as socket closures.
Non-standard moments:
process.nextTick(): Executes between event loop phases and before any callback in the current phase. Has higher priority.- Promises: Promise handlers (
.then(),.catch(),.finally()) also execute as microtasks, immediately after the current operational task or function, before the event loop moves to the next phase or processes other macrotasks (like timers or I/O).
Structure of phases:
┌───────────────┐
┌─>│ timers │
│ └───────────────┘
│ ┌───────────────┐
│ │ pending callbacks │
│ └───────────────┘
│ ┌───────────────┐
│ │ idle, prepare │
│ └───────────────┘ ┌───────────────┐
│ ┌───────────────┐ │ poll │
└──┤ poll ├───>│ (I/O callbacks, check timers) │
└───────────────┘ └───────────────┘
┌───────────────┐
│ check │
└───────────────┘
┌───────────────┐
│ close callbacks │
└───────────────┘
Example of setImmediate vs setTimeout execution:
// setImmediate executes in the check phase,
// setTimeout in the timers phase.
// The order of execution depends on external I/O factors,
// but setImmediate is guaranteed to run after the current poll phase.
setTimeout(() => {
console.log('setTimeout 0ms');
}, 0);
setImmediate(() => {
console.log('setImmediate');
});
Example of process.nextTick execution:
// process.nextTick() executes before setImmediate and setTimeout,
// even if they have zero delay.
process.nextTick(() => {
console.log('process.nextTick');
});
setTimeout(() => {
console.log('setTimeout 0ms');
}, 0);
setImmediate(() => {
console.log('setImmediate');
});