KatInterview

Predicting Output Order with the Browser Event Loop

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesjavascriptevent-loopasync

Last updated

Work out the print order of a short script mixing timers, promises and microtasks, then explain how the browser event loop schedules each kind of task.

Scheduling in a Single-Threaded Runtime

JavaScript runs your code on one thread, yet pages stay responsive while timers, network calls and promises are in flight. The event loop makes that possible.

Consider this script, executed as a normal top-level script in a modern browser:

console.log('first');

setTimeout(() => console.log('timer'), 0);

Promise.resolve().then(() => console.log('promise'));

queueMicrotask(() => console.log('micro'));

console.log('last');

What to cover

  1. State the exact order in which the five messages are printed, and justify it step by step.
  2. Explain the difference between a macrotask (for example a setTimeout callback) and a microtask (for example a .then callback or a queueMicrotask callback).
  3. Describe what the event loop does once the call stack becomes empty, and in what order it picks the next piece of work.
  4. Say what happens when a microtask schedules another microtask, and what happens if that never stops.

Assumptions

  • A standard modern browser, not Node.js.
  • Think in terms of the call stack, the task queue and the microtask queue.
  • Mention, briefly, how async/await fits into the same model.

Hints

Hint 1

Start by separating what runs immediately on the call stack from what is merely queued for later. Only two of the five lines are purely synchronous.

Hint 2

There are two different queues. Ask which one is emptied completely before the loop moves on, and where the top-level script itself fits in (it is a task too).

Hint 3

A microtask that enqueues another microtask is appended to the same queue and runs in the same drain. Think about what that implies for a microtask that keeps re-enqueueing itself.