Node.js

The Node.js Event Loop in Plain Language

By MinorNode Editorial Team · · 5 min read

Node.js runs your JavaScript on a single main thread, yet a Node server can talk to thousands of clients at once. That sounds like a contradiction until you meet the event loop, the mechanism that decides what runs next and what waits.

You do not need to read the source code to understand it. A good mental picture, plus a few rules about what blocks it, is enough to write faster and safer backend code.

The Restaurant Analogy

Imagine a restaurant with one waiter. The waiter takes an order, hands it to the kitchen, and immediately moves on to the next table. When the kitchen rings a bell, the waiter picks up the finished dish and delivers it. The waiter never stands in front of the stove waiting for the soup to cook.

In Node.js, your JavaScript code is the waiter. Slow work such as reading a file, querying a database or calling another service is the kitchen. The event loop is the waiter's routine of checking tables, ringing bells and deciding what to do next.

The key idea is that waiting is not the same as working. While a database query is in flight, the main thread is free to do something else.

What the Event Loop Actually Does

When you start a Node program, it runs your script from top to bottom. That first pass is synchronous: every line finishes before the next begins. Then Node enters the event loop and keeps cycling as long as there is something left to do, such as an open server, a pending timer or an unfinished request.

On each cycle the loop looks for work that is ready and runs the matching callback. A callback is simply a function you handed to Node earlier and said "call this when the thing is done".

Heavy lifting like network and file operations is handed off to the operating system or to a small pool of helper threads managed by a library called libuv. When those operations finish, their results are queued up so the event loop can pick them up.

The Phases, Simplified

The loop moves through a fixed order of phases. You rarely need all the details, but knowing the main ones explains a lot of surprising behavior.

  • Timers: runs callbacks scheduled by setTimeout and setInterval whose time has come.
  • Pending callbacks: handles certain deferred system-level callbacks.
  • Poll: collects new input and output events, such as an incoming network request or a finished file read, and runs their callbacks.
  • Check: runs callbacks scheduled with setImmediate.
  • Close callbacks: runs cleanup handlers, for example when a socket closes.

Between these steps, Node also drains two small queues of urgent work: the process.nextTick queue and the promise microtask queue. These run before the loop moves on to the next phase, which means they can jump ahead of timers.

A Small Example

Consider this snippet.

console.log('A');

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

Promise.resolve().then(() => console.log('C'));

console.log('D');

The output is A, D, C, B. The two synchronous logs run first. The promise callback runs next because microtasks are processed as soon as the current code finishes. The timer callback runs last, since even a delay of zero milliseconds still has to wait for the loop to reach the timers phase.

If you can predict this order, you understand the core of the event loop.

How to Block the Event Loop by Accident

Because there is one main thread, any long synchronous job freezes everything else. While your code is busy, no new requests are accepted and no callbacks run.

Common causes include:

  • Parsing or building a very large JSON string in one go.
  • Running a tight loop over millions of items.
  • Using synchronous file functions such as readFileSync inside a request handler.
  • Heavy cryptographic or compression work done on the main thread.
  • A regular expression that backtracks badly on certain input.

Startup scripts can use synchronous calls without harm, since nothing else is waiting. Inside request handling, they are a trap.

Keeping the Loop Healthy

A few habits keep a Node server responsive.

  1. Prefer the asynchronous version of an API, using promises or async and await.
  2. Split large jobs into smaller chunks and yield between them, for example with setImmediate.
  3. Move CPU-heavy work to worker threads or to a separate process.
  4. Measure event loop delay in production, so you notice when something starts hogging the thread.

Remember that async and await do not create new threads. They are a friendlier way to write code that waits. A function marked async still runs on the main thread until it reaches an await on something that is genuinely asynchronous.

When Node Is Not the Right Tool

The event loop shines for input and output heavy programs: web servers, API backends, chat services and proxies. It is a weaker fit for long number-crunching tasks, because those compete with request handling for the same thread. You can still use Node in those cases, but plan to offload the heavy parts.

Frequently Asked Questions

Is Node.js really single-threaded?

Your JavaScript runs on one main thread, but Node itself is not purely single-threaded. Its libuv layer uses a pool of background threads for tasks like file system work and DNS lookups, and you can add your own threads with worker threads. The single thread is simply where your callbacks execute.

What is the difference between setTimeout and setImmediate?

setTimeout schedules a callback for the timers phase after at least the given delay, while setImmediate schedules it for the check phase right after polling. From the main module their order can vary, but inside an input or output callback setImmediate always fires first.

Why does my server stop responding during a heavy calculation?

The calculation is running synchronously on the main thread, so the event loop cannot process any other request until it finishes. Break the work into smaller pieces, or move it to a worker thread or another process so the loop stays free.

Related reading