#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 23 of 62medium

How does the Event Loop work in Node.js?

Understanding the Node.js event loop and its phases.

What You'll Learn

  • How the event loop works
  • Event loop phases
  • Understanding async behavior

Event Loop Overview

The Event Loop is what allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded.

Event Loop Phases

code.jsJavaScript
┌───────────────────────────┐
┌─>│           timers           (setTimeout, setInterval)
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │     pending callbacks      (I/O callbacks)
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │       idle, prepare        (internal use)
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │           poll             (retrieve new I/O events)
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │           check            (setImmediate)
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
└──┤      close callbacks       (socket.on('close'))
   └───────────────────────────┘

Example

code.jsJavaScript
console.log('Start');

setTimeout(() => console.log('Timeout'), 0);

setImmediate(() => console.log('Immediate'));

process.nextTick(() => console.log('NextTick'));

console.log('End');

// Output: Start, End, NextTick, Timeout/Immediate

Key Points

  • process.nextTick() runs before event loop continues
  • setImmediate() runs in check phase
  • setTimeout(0) runs in timers phase