agyanadda@gmail.com

Node.js Event Loop

Asynchronous Programming 1 min read Updated Dec 3, 2026 Topic 11 of 30

Node.js runs your JavaScript on one thread, yet handles thousands of users. The secret is the event loop.

How it works

  1. Your code runs on the call stack
  2. Slow work (files, network, timers) is handed to the system and Node's thread pool
  3. When that work finishes, its callback is put in a queue
  4. When the stack is empty, the event loop takes the next callback and runs it

Order of execution

  1. Synchronous code
  2. Microtasks: process.nextTick, then resolved Promises
  3. Timers (setTimeout, setInterval)
  4. I/O callbacks
  5. setImmediate (check phase)

The golden rule

Don't block the event loop. A long loop, readFileSync, or heavy CPU work (resizing images, big calculations) stops every user's request. Use async functions, streams, or worker threads for heavy CPU tasks.

Example

Example — Guess the output order JavaScript
console.log('1: start');

setTimeout(() => console.log('5: setTimeout'), 0);
setImmediate(() => console.log('6: setImmediate'));

Promise.resolve().then(() => console.log('4: promise'));
process.nextTick(() => console.log('3: nextTick'));

console.log('2: end');

Output: 1: start, 2: end, 3: nextTick, 4: promise, 5: setTimeout, 6: setImmediate. Sync code runs first, then microtasks, then timers. (setTimeout vs setImmediate order can vary in the main script, but microtasks always come first.)

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which runs first?

Exercise 2 True / False

A long synchronous loop blocks all other requests in Node.js.

Exercise 3 Fill in the Blank

Node.js runs your JavaScript on a ___ thread.

Frequently Asked Questions

Move it off the main thread with the worker_threads module, a job queue processed by a separate worker process, or a service written for heavy computing. Keep the main thread free for requests.