← Back to Node.js Course | Chapter 1: Introduction | Lesson 3 of 7

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:

  1. Event loop

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

javascript
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
  1. Expecting setTimeout 0 to run immediately
  2. Forgetting promises run before timers
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.