MohitDecodes
Back to blogsJavaScript

The JavaScript Event Loop, Microtasks, and Output Questions Explained

November 18, 2026 · 7 min read

Output-prediction questions around `setTimeout` and `Promise.then` are a staple of JavaScript interviews — not as trivia, but because they reveal whether you understand how single-threaded JavaScript schedules async work.

Predict the output first

console.log("1");

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

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

console.log("4");
// Output: 1, 4, 3, 2

Why 3 runs before 2

JavaScript executes synchronous code on the call stack first (`1` and `4`). Asynchronous callbacks don't all go into the same line: Promise callbacks (`.then`, `catch`, `finally`, and the code after `await`) go into the **microtask queue**, while `setTimeout`, `setInterval`, and DOM events go into the **task (macrotask) queue**.

  • 1. Run synchronous code until the call stack is completely empty.
  • 2. Drain the entire microtask queue before moving on (including new microtasks queued by microtasks).
  • 3. Pick one task from the macrotask queue (like `setTimeout`), execute it, then drain microtasks again.

Once you trace code with those three steps instead of guessing, almost every `async`/`await`, Promise, and `setTimeout` interview question becomes mechanical.

Further reading