Phases of the Event Loop
The event loop runs in phases. Each phase handles one kind of waiting work.
Timers run in delay order
The zero timer runs before the 100 millisecond timer. The main code runs first.
setTimeout(() => {
console.log("Timer phase");
}, 0);
console.log("Main code");The check phase
setImmediate runs its function in the check phase. The main code still runs first.
setImmediate(() => {
console.log("Check phase");
});
console.log("Main code");Example
console.log("Start");
setTimeout(() => {
console.log("After 100 ms");
}, 100);
setTimeout(() => {
console.log("After 0 ms");
}, 0);
console.log("End");Key points
- A phase is one step of the loop, and each step has its own job.
- The timers phase runs callbacks from setTimeout and setInterval.
- The poll phase waits for new work to finish.
- The check phase runs callbacks from setImmediate.
- setImmediate runs a function in the check phase.
- The close phase runs cleanup callbacks when work closes.
- The loop repeats its phases until no work is left.
In this example, the first print shows Start at once. Two timers start, one for 100 milliseconds and one for zero. The next print shows End while both timers wait. The timers phase then runs the zero timer first and the 100 millisecond timer last.
Note
Timers with shorter delays run before timers with longer delays.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which phase runs setTimeout callbacks?