The Event Loop

How single-threaded JavaScript handles concurrency — the call stack, Web APIs, the task (macrotask) queue, the microtask queue, rendering, and Node.js event loop phases — with an interactive visualiser and output-ordering puzzles.

Intermediate 3 min readLesson 6 of 12 Interview Q&A

JavaScript runs your code on a single thread: one call stack, one thing at a time. Yet a browser tab handles clicks, timers, network responses and animations "at once", and Node.js serves thousands of connections. The trick is the event loop: slow operations happen outside JavaScript (in the browser or libuv), and their callbacks are queued to run on the main thread when it's free.

The pieces

start async workpush callbackCall stackruns one frame at a timeWeb APIs / libuvtimers · network · DOM events · fsMicrotask queuepromise callbacks · queueMicrotaskTask queuesetTimeout · I/O · eventsEvent loop
  • Call stack: where synchronous code executes.
  • Host APIs: the environment does the waiting (timers, sockets, file reads) on other threads or OS facilities.
  • Task queue (macrotasks): callbacks from setTimeout, setInterval, I/O, UI events, MessageChannel.
  • Microtask queue: promise reactions (.then, await continuations), queueMicrotask, MutationObserver.

The algorithm

  1. Run the current script (itself a task) until the call stack is empty.
  2. Drain the microtask queue completely — including microtasks added while draining.
  3. (Browser) If it's time, render: run requestAnimationFrame callbacks, style, layout, paint.
  4. Take one task from the task queue and run it.
  5. Go to step 2.

The crucial rule: all microtasks run before the next task. Promises always beat setTimeout(fn, 0).

Try it

InteractiveThe JavaScript event loop
1console.log('A');
2setTimeout(() => console.log('B'), 0);
3Promise.resolve().then(() => console.log('C'));
4queueMicrotask(() => console.log('D'));
5console.log('E');
Call stack
main()
Web APIs / host
empty
Microtask queue
empty
Macrotask queue
empty
Console
empty
Script starts: the whole file runs as one macrotask on the call stack.
1/12

Ordering puzzles

JavaScript
console.log("1: script start");

setTimeout(() => console.log("2: timeout"), 0);

Promise.resolve()
  .then(() => console.log("3: microtask 1"))
  .then(() => console.log("4: microtask 2"));

queueMicrotask(() => console.log("5: queueMicrotask"));

console.log("6: script end");

Output:

1: script start
6: script end
3: microtask 1
5: queueMicrotask
4: microtask 2
2: timeout

Synchronous code first (1, 6). Then microtasks in queue order: 3 and 5 were queued during the script; 4 is queued only when 3 finishes, so it comes after 5. Finally the timeout task.

async/await is microtasks

JavaScript
async function f() {
  console.log("A");
  await null;               // everything after this is a microtask continuation
  console.log("B");
}
console.log("start");
f();
console.log("end");
// start, A, end, B

An async function runs synchronously until its first await; the rest resumes as a microtask.

A harder one

JavaScript
setTimeout(() => console.log("t1"), 0);
setTimeout(() => {
  console.log("t2");
  Promise.resolve().then(() => console.log("t2 micro"));
}, 0);
setTimeout(() => console.log("t3"), 0);
Promise.resolve().then(() => console.log("m1"));
// m1, t1, t2, t2 micro, t3

After each task (t2), the microtask queue is drained ("t2 micro") before the next task (t3).

Blocking the loop

While JavaScript runs, nothing else happens: no clicks, no rendering, no other callbacks.

JavaScript
button.onclick = () => {
  const end = Date.now() + 3000;
  while (Date.now() < end) {}   // the page is frozen for 3 seconds
};

How to keep the main thread responsive:

  • Split long work into chunks and yield between them (await scheduler.yield(), or setTimeout(resolve, 0)).
  • Move CPU-heavy work to a Web Worker (a separate thread with its own event loop; communicate via postMessage).
  • Use requestAnimationFrame for visual updates and requestIdleCallback for low-priority work.

Timers aren't precise

setTimeout(fn, 100) means "at least 100 ms": the callback is queued after 100 ms and runs when the stack is empty and earlier tasks are done. Browsers clamp nested timers to ≥ 4 ms and throttle timers in background tabs.

Node.js: the libuv event loop

Node uses the same model with a more detailed task loop, in phases:

timerssetTimeout / setInterval callbacks whose time has comepending callbackssome deferred system I/O callbackspollretrieve new I/O events and run their callbacks; may block waitingchecksetImmediate callbacksclose callbackssocket.on('close')…

Between every callback, Node drains process.nextTick callbacks first, then promise microtasks.

JavaScript
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));
// nextTick, promise, then timeout/immediate (order of these two varies in the main module;
// inside an I/O callback, setImmediate always comes first)

File system operations, DNS lookups and crypto run on libuv's thread pool (4 threads by default); network sockets use the OS's non-blocking APIs (epoll, kqueue, IOCP). See Node.js internals.

Key takeaways
  • One call stack; the host does async work and queues callbacks.
  • After each task, the entire microtask queue is drained, then (in browsers) rendering may happen.
  • Promises/await continuations are microtasks and run before setTimeout callbacks.
  • Long synchronous work or endless microtasks block everything; chunk work or use workers.
  • Node adds phases (timers, poll, check…) plus process.nextTick, which runs before promises.
Interview questions
QExplain the event loop.medium

JavaScript executes on one thread with a call stack. Asynchronous operations are handed to the host environment, which queues their callbacks when ready: promise reactions go to the microtask queue, timers, I/O and events to the task queue. Whenever the call stack empties, the event loop drains all microtasks, lets the browser render if needed, then runs the next task, and repeats. This gives concurrency without multithreading in user code.

QWhy does a resolved promise's then callback run before setTimeout(fn, 0)?medium

then callbacks are microtasks, setTimeout callbacks are tasks. After the current script (a task) finishes, the event loop drains the entire microtask queue before taking the next task, so all pending promise reactions run first.