Explain event loop in Node.js

MediumTechnical
AmazonBackend Engineer
178

How does the event loop work in Node.js? Explain the different phases and how async operations are handled.

1 Answer

167
Top Answer

The event loop has 6 phases:

Phases (in order)

  1. timers - Execute setTimeout/setInterval callbacks
  2. pending callbacks - Execute I/O callbacks deferred from previous cycle
  3. idle, prepare - Internal use only
  4. poll - Retrieve new I/O events
  5. check - Execute setImmediate callbacks
  6. close callbacks - Handle close events (socket.on('close'))
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
process.nextTick(() => console.log('nextTick'));
Promise.resolve().then(() => console.log('promise'));

// Output:
// nextTick
// promise
// timeout (or immediate)
// immediate (or timeout)

Priority

  1. process.nextTick() - runs between phases
  2. Microtasks (Promises) - after nextTick
  3. Macrotasks (setTimeout, setImmediate)
NodeJSGuru

Share Your Answer

Help others by sharing your knowledge and experience with this question.

Coming soon...

Related Questions

View all

More from Amazon

View all