Skip to content
Velloreth
Programming 6 min read

The Event Loop Explained: How JavaScript Runs Async Code

JavaScript is single-threaded yet handles concurrency. Learn the call stack, task queues, microtasks, and why setTimeout has a minimum delay.

By

The single-threaded puzzle

JavaScript is single-threaded. It has one call stack and executes one thing at a time. Yet a web page can fetch data, animate, respond to clicks, and run timers simultaneously.

The resolution is that JavaScript does not do those things itself. The runtime — the browser or Node — provides the concurrency, and the event loop coordinates it.

The model has four parts:

  1. Call stack — where function calls execute.
  2. Web APIs / Node APIs — where timers, network requests, and I/O actually run, off the main thread.
  3. Task queues — where completed callbacks wait.
  4. Event loop — which moves callbacks from the queues to the stack when it is empty.

The call stack

The call stack tracks where you are in the program. Each function call pushes a frame; each return pops one.

function a() { b(); }
function b() { c(); }
function c() { console.log('done'); }

a();

The stack grows as a calls b calls c, then unwinds. If it grows too deep, you get a stack overflow — which is exactly what happens with runaway recursion.

The stack is the reason JavaScript is single-threaded in the sense that matters: only one function is executing at any moment.

The event loop in action

console.log('1');

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

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

console.log('4');

The output is 1, 4, 3, 2. This surprises almost everyone the first time.

Here is why:

  1. console.log('1') runs synchronously. Output: 1.
  2. setTimeout hands the callback to the runtime, which starts a timer. The callback is queued as a macrotask.
  3. Promise.resolve().then(...) queues the callback as a microtask.
  4. console.log('4') runs synchronously. Output: 4.
  5. The synchronous code is done. The event loop drains the microtask queue first. Output: 3.
  6. Then it takes the next macrotask. Output: 2.

The rule: microtasks before macrotasks, and the microtask queue drains completely before the next macrotask.

Microtasks vs macrotasks

MicrotasksMacrotasks
SourcesPromises, queueMicrotask, MutationObserversetTimeout, setInterval, I/O, events
When they runAfter the current task, before the next macrotaskOne per event loop iteration
Queue behaviourEntire queue drainsOne task per iteration

The distinction matters because a microtask can starve the event loop. If a microtask queues another microtask, the queue never empties and the next macrotask never runs.

// This hangs the page forever
function loop() {
  Promise.resolve().then(loop);
}
loop();

The same code with setTimeout would not hang, because each iteration yields to the event loop.

Why setTimeout(fn, 0) is not immediate

setTimeout with a delay of 0 does not run the callback immediately. It queues a macrotask, which runs only after:

  1. The current synchronous code finishes.
  2. All pending microtasks drain.
  3. The browser has had a chance to render.

Browsers also clamp the delay. After five nested timers, the minimum becomes 4 milliseconds. In background tabs, timers are throttled to once per second or more.

So setTimeout(fn, 0) means “as soon as possible after the current work and all microtasks”, not “now”.

Blocking the event loop

Because there is one thread, long synchronous work blocks everything.

// Freezes the page for several seconds
function slowSum() {
  let total = 0;
  for (let i = 0; i < 10_000_000_000; i++) total += i;
  return total;
}

While this runs, no clicks are handled, no timers fire, and nothing renders. The page is frozen.

The fixes:

Chunk the work. Break the loop and yield between chunks:

function chunkedSum(total, callback) {
  let sum = 0;
  let i = 0;
  function step() {
    const end = Math.min(i + 1_000_000, total);
    for (; i < end; i++) sum += i;
    if (i < total) setTimeout(step, 0);
    else callback(sum);
  }
  step();
}

Move it off the main thread. A Web Worker runs in a separate thread:

const worker = new Worker('worker.js');
worker.postMessage({ n: 10_000_000_000 });
worker.onmessage = (e) => console.log(e.data);

Use an async API. fs.promises.readFile does not block; fs.readFileSync does.

Rendering and the event loop

In browsers, the event loop also handles rendering. The cycle is roughly:

  1. Run one macrotask.
  2. Drain the microtask queue.
  3. If needed, run requestAnimationFrame callbacks.
  4. Recalculate styles, layout, and paint.
  5. Repeat.

This is why requestAnimationFrame is the right place for animation: it runs just before the browser paints, so your changes are included in that frame.

function animate() {
  element.style.transform = `translateX(${x++}px)`;
  if (x < 100) requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

Using setTimeout for animation instead produces jank, because the timing does not align with the render cycle.

The event loop in Node

Node’s event loop has distinct phases:

PhaseHandles
TimerssetTimeout, setInterval
Pending callbacksDeferred I/O callbacks
PollRetrieve new I/O events
ChecksetImmediate callbacks
CloseClose event callbacks

Node also has process.nextTick, which is not a microtask in the browser sense but runs before the microtask queue drains — it has the highest priority.

process.nextTick(() => console.log('nextTick'));
Promise.resolve().then(() => console.log('promise'));
setImmediate(() => console.log('immediate'));

The order is nextTick, promise, immediate. process.nextTick is the most immediate, and overusing it starves the event loop just as microtasks do.

Common misconceptions

“setTimeout(fn, 0) runs immediately.” It queues a macrotask. Microtasks run first.

“Promises are asynchronous.” The .then callback is asynchronous, but the promise executor runs synchronously:

console.log('a');
new Promise((resolve) => {
  console.log('b'); // runs synchronously!
  resolve();
});
console.log('c');
// a, b, c

“await blocks the thread.” It suspends the async function, not the program.

“JavaScript is multi-threaded because of workers.” Workers are separate threads with separate stacks. They communicate by message passing, not shared memory (except with SharedArrayBuffer).

“The event loop is part of the language.” It is part of the runtime. The language specification defines promises and jobs; the host defines the loop.

Practical guidance

  • Keep synchronous work short. Anything over about 50 milliseconds is noticeable.
  • Prefer async APIs over their sync counterparts in servers and browsers.
  • Use Web Workers for CPU-heavy work.
  • Use requestAnimationFrame for visual updates.
  • Do not starve the microtask queue with recursive promise chains.
  • Remember the ordering — sync, then microtasks, then macrotasks.
  • Profile before optimising — the event loop is rarely the bottleneck until it is.

For the async patterns built on this, see promises vs async/await and callbacks explained. For the browser performance angle, improve inp core web vitals static site and how cdns actually work.

Quotable summary

JavaScript runs on a single thread with a call stack, and the event loop moves queued callbacks onto that stack whenever it is empty. Microtasks from promises run before macrotasks from timers and I/O, and the entire microtask queue drains before the next macrotask begins. setTimeout(fn, 0) queues a macrotask that runs after all pending microtasks and after the browser has had a chance to render, which is why it is not immediate. Blocking the call stack blocks rendering, input, and timers, so long synchronous work freezes the page; the fixes are chunking, Web Workers, and async APIs. The event loop is a runtime feature, and Node’s implementation has additional phases including setImmediate and process.nextTick.

Frequently asked questions

What is the event loop in simple terms?
The event loop is a mechanism that lets a single-threaded language handle many operations at once. It watches a queue of pending callbacks and runs them one at a time whenever the call stack is empty.
Why is JavaScript single-threaded?
Because it was designed for the browser, where multiple threads mutating the same DOM would create race conditions. A single thread with an event loop avoids that class of bug entirely, at the cost of needing to keep work short.
What is the difference between a microtask and a macrotask?
Microtasks come from promises and queueMicrotask; macrotasks come from timers, I/O, and events. After each macrotask, the entire microtask queue drains before the next macrotask runs, so promises always resolve before timers.
Why does setTimeout with 0 delay not run immediately?
Because it queues a macrotask, which only runs after the current synchronous code finishes and all pending microtasks drain. Browsers also clamp the delay to a minimum of about 4 milliseconds after nested timers.
What is the difference between the event loop in Node and the browser?
Node has additional phases for timers, pending callbacks, polling, and check, plus setImmediate and process.nextTick. Browsers have rendering steps and requestAnimationFrame. The core idea is the same but the details differ.
How do I avoid blocking the event loop?
Keep synchronous work short, break large loops into chunks with setTimeout or setImmediate, move heavy computation to a Web Worker or worker thread, and prefer asynchronous I/O APIs over their synchronous counterparts.