Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Tools
Back to Node.js
Understanding the Node.js Event Loop

Understanding the Node.js Event Loop

Node.jsBy Muhammad Fareed
nodejsunderstandingeventloop

Short answer: Node.js runs your JavaScript on a single thread. The event loop lets it handle many operations at once without blocking: slow work (network, files, timers) is handed off, and when it finishes its callback is queued and run when the call stack is free.

Why a loop at all?

JavaScript can run one piece of code at a time. If a request waited for a database reply, every other user would wait too. Instead Node starts the operation, keeps running other code, and returns to the result later. The event loop is the mechanism that picks up those results.

The big picture

  1. Your synchronous code runs on the call stack until it finishes.
  2. Asynchronous work (timers, file I/O, network) is performed by the operating system or by libuv's thread pool.
  3. When that work completes, its callback goes into a queue.
  4. The event loop takes callbacks from the queues and runs them whenever the stack is empty.

The phases of the loop

PhaseWhat runs
TimersCallbacks from setTimeout and setInterval that are due
Pending callbacksSome deferred system callbacks
PollRetrieves new I/O events and runs their callbacks
ChecksetImmediate callbacks
Close callbacksCleanup such as socket.on("close")

Between each phase (and after each callback), Node runs the microtask queues: first process.nextTick callbacks, then promise callbacks.

Order of execution: an example

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");

Typical output:

1: start
2: end
3: nextTick
4: promise
5: setTimeout
6: setImmediate

Synchronous code finishes first. Then nextTick, then promises, then timers and setImmediate. When called from the main module, the order of setTimeout(..., 0) and setImmediate can vary, but inside an I/O callback setImmediate always runs first.

Blocking the loop

Because there is only one thread for your code, a long synchronous task freezes everything:

// Blocks every request for several seconds
app.get("/slow", (req, res) => {
  let sum = 0;
  for (let i = 0; i < 1e10; i++) sum += i;
  res.send(String(sum));
});

Avoid CPU-heavy loops, large synchronous JSON parsing and *Sync file functions in servers. Move heavy work to a worker thread (worker_threads), a child process or a separate service.

Thread pool

Some operations (file system, DNS lookup, crypto, zlib) run in libuv's thread pool, 4 threads by default, adjustable with UV_THREADPOOL_SIZE. Your JavaScript still runs on one thread; only the underlying work is parallel.

Tips

  • Prefer asynchronous APIs and async/await. See promises and async/await.
  • Do not overuse process.nextTick: recursive calls can starve I/O.
  • Stream large data instead of loading it all at once: Node.js streams.
  • Measure event-loop delay if your server feels slow.

Background reading: what is Node.js.

FAQs

Is Node.js really single-threaded?

Your JavaScript runs on one main thread, but Node uses other threads internally for some I/O and you can start worker threads yourself.

What is the difference between setImmediate and setTimeout(0)?

setImmediate runs in the check phase after I/O. setTimeout(0) runs in the timers phase after at least about 1 ms. Their order from the main module is not guaranteed.

Where do promises run?

In the microtask queue, right after the current operation and before the loop moves to the next phase.

How do I find out if I am blocking the loop?

Watch for slow responses under light load, and use profiling tools or event-loop-delay monitoring.