0
0
NodejsHow-ToBeginner · 4 min read

How Event Loop Works in Node.js: Simple Explanation and Example

The event loop in Node.js is a mechanism that allows non-blocking I/O by handling asynchronous callbacks in a single thread. It continuously checks the callback queue and executes tasks when the call stack is empty, enabling efficient concurrency without multiple threads.
📐

Syntax

The event loop itself is not a function you call directly but a built-in mechanism in Node.js that runs automatically. You interact with it indirectly by using asynchronous functions like setTimeout(), fs.readFile(), or promises.

Key parts involved:

  • Call Stack: Where your code runs line by line.
  • Callback Queue: Holds callbacks waiting to run after async tasks complete.
  • Event Loop: Checks if the call stack is empty and moves callbacks from the queue to the stack.
javascript
setTimeout(() => {
  console.log('This runs after 1000ms');
}, 1000);

console.log('This runs first');
Output
This runs first This runs after 1000ms
💻

Example

This example shows how Node.js runs synchronous code first, then asynchronous callbacks via the event loop.

javascript
console.log('Start');

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

console.log('End');
Output
Start End Timeout callback
⚠️

Common Pitfalls

Developers often expect asynchronous callbacks with setTimeout(fn, 0) to run immediately, but they run only after the current code finishes. Blocking the call stack with heavy synchronous code delays all callbacks.

Also, mixing synchronous and asynchronous code without understanding the event loop can cause unexpected order of execution.

javascript
console.log('Before blocking');

// Blocking synchronous loop
const start = Date.now();
while (Date.now() - start < 2000) {}

setTimeout(() => {
  console.log('After blocking');
}, 0);

console.log('After blocking code');
Output
Before blocking After blocking code After blocking
📊

Quick Reference

Event Loop Phases:

  • Timers: Executes callbacks scheduled by setTimeout and setInterval.
  • Pending Callbacks: Executes I/O callbacks deferred to the next loop iteration.
  • Idle, Prepare: Internal use.
  • Poll: Retrieves new I/O events; executes I/O related callbacks.
  • Check: Executes setImmediate callbacks.
  • Close Callbacks: Executes close event callbacks like socket.on('close').

Understanding these helps predict callback execution order.

Key Takeaways

Node.js event loop runs asynchronous callbacks when the call stack is empty.
Synchronous code blocks the event loop and delays async callbacks.
setTimeout with 0 delay still runs after current synchronous code finishes.
Event loop phases determine the order of callback execution.
Understanding event loop helps write efficient, non-blocking Node.js code.