What is the Event Loop?

The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous work: it repeatedly takes the next task from a queue, runs it to completion on the call stack, drains all microtasks, and (in browsers) lets the page render.

The pieces

  • Call stack: where JavaScript actually runs, one frame at a time.
  • Host APIs (browser or Node): timers, network, I/O and events run outside the JavaScript thread and queue callbacks when done.
  • Task queue (macrotasks): setTimeout, setInterval, I/O, UI events, MessageChannel.
  • Microtask queue: promise reactions (.then, await continuations), queueMicrotask, MutationObserver.

One iteration of the loop

  1. Take the oldest task and run it until the stack is empty.
  2. Run all microtasks, including ones queued during this step.
  3. In browsers, possibly render (style, layout, paint), running requestAnimationFrame callbacks just before.
  4. Repeat.

Consequences

  • setTimeout(fn, 0) is "as soon as possible after the current task and its microtasks", never immediate.
  • Promise callbacks always run before the next timer.
  • Long synchronous work or an endless microtask loop blocks rendering and input. Split heavy work into chunks, or move it to a Web Worker.
  • await pauses only the async function; the rest of the program keeps going.

Node.js

Node's loop has phases (timers, poll for I/O, check for setImmediate, close callbacks), and process.nextTick callbacks run even before promise microtasks.

Code example

js
1console.log("1 script start");
2
3setTimeout(() => console.log("6 timeout (task)"), 0);
4
5Promise.resolve()
6 .then(() => console.log("4 promise 1 (microtask)"))
7 .then(() => console.log("5 promise 2 (microtask)"));
8
9queueMicrotask(() => console.log("4b queueMicrotask"));
10
11(async () => {
12 console.log("2 async fn runs synchronously until await");
13 await null;
14 console.log("4c after await (microtask)");
15})();
16
17console.log("3 script end");
18
19// Real output order:
20// 1 script start
21// 2 async fn runs synchronously until await
22// 3 script end
23// 4 promise 1, 4b queueMicrotask, 4c after await (microtasks, in queue order)
24// 5 promise 2
25// 6 timeout (task)

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app