JavaScript Interview Question: How Does the Event Loop Work?

A
Author
06 Sep, 2026 1 min read 400 views

Short answer: JavaScript runs on a single thread with a call stack. Async work (timers, network, I/O) is handled by the environment, which queues callbacks. The event loop takes the next callback when the stack is empty, always draining all microtasks before the next task (macrotask).

The pieces

  • Call stack - the code currently running.
  • Task queue - setTimeout, setInterval, I/O, UI events.
  • Microtask queue - promise callbacks (.then, await continuations), queueMicrotask.

The classic question

console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');

// Output: 1, 4, 3, 2
  1. 1 and 4 run synchronously on the stack.
  2. The stack empties; all microtasks run: 3.
  3. Then the next task: the timer callback, 2.

With async/await

async function run() {
  console.log('A');
  await null;           // the rest of the function becomes a microtask
  console.log('B');
}
run();
console.log('C');
// A, C, B

Why it matters in practice

  • Long synchronous work blocks everything: clicks, rendering, other requests in Node.js.
  • setTimeout(fn, 0) doesn't run "immediately"; it waits for the stack and all microtasks.
  • In browsers, rendering happens between tasks, so a huge chain of microtasks can also delay painting.
Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.