Practice · JavaScript

The event loop, step by step

Pick a program and guess what it prints. Then step through it: the call stack, the timers, the microtask and task queues, and the console. Every program here prints in Node exactly what the steps show.

A timer of 0 ms still waits for the script and every microtask. Promises go first.

1console.log("A");2setTimeout(() => console.log("B"), 0);3Promise.resolve().then(() => console.log("C"));4console.log("D");

Call stack

  • global (the script)

Timers (Web APIs)

none waiting

Microtask queue

empty

Task queue

empty

Console

Step 1 of 14. The whole script runs first, as one task, on the call stack.

The rule that answers every question

  1. Run the whole script, all the synchronous code, to the end.
  2. Run every microtask, including the ones added while doing so.
  3. Take one task (like a timer's callback), run it, then go back to step 2.

Microtasks and tasks

  • Microtasks: .then, .catch and .finally callbacks, the code after an await, and queueMicrotask.
  • Tasks (also called macrotasks): setTimeout and setInterval callbacks, events, and I/O.

Exam traps

  • setTimeout(fn, 0) doesn't mean now: it waits for the script and for every microtask.
  • The function you pass to new Promise runs straight away. Only .then waits.
  • An async function runs synchronously until its first await.

Learn it properly in Inside JavaScript: the event loop,promises and async/await. Then test yourself with the code-reading drills.