Event loop
The event loop is the never-ending cycle that picks finished tasks off a queue and runs them one at a time.
In this page:
Event loop
After your main script runs, Node enters the event loop, which cycles through phases: timers, pending callbacks, poll (I/O), check (setImmediate) and close callbacks.
Microtasks such as promise callbacks and process.nextTick run between operations. Understanding the order explains many surprising outputs.
Note:
process.nextTick callbacks run before promise microtasks, and both run before timers.
Example: Event loop
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");
// Output:
// sync
// nextTick
// promise
// timeout
// immediate
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Expecting setTimeout 0 to run immediately
- Forgetting promises run before timers
- Starving the loop with endless nextTick calls
Chapter Summary
- The event loop cycles through phases
- Microtasks run between phases
- nextTick runs before promises
- Timers run after microtasks
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: