mediumJS ES5#140

Predict the event-loop order

Prompt

Given this snippet, write predictOrder() returning the labels in the exact order they log:

log('A')
setTimeout(() => log('B'), 0)
Promise.resolve().then(() => log('C'))
Promise.resolve().then(() => {
  log('D')
  setTimeout(() => log('E'), 0)
})
log('F')

Return an array of strings. No guessing — reason through sync → microtasks → macrotasks.

Solution

function predictOrder() {
  // 1. Synchronous code runs to completion: A, F
  // 2. Microtask queue drains fully: C, D (D enqueues a NEW macrotask E)
  // 3. Macrotasks run one per tick, oldest first: B, then E
  return ['A', 'F', 'C', 'D', 'B', 'E']
}
Mentor's take

This ordering question is the fastest senior/junior separator in JavaScript interviews because it tests the model, not memorization: the call stack runs to completion, then the engine drains the entire microtask queue, and only then takes one macrotask — and repeats.

Walk it like a mentor would:

  1. Sync first, always. A and F print before any callback — nothing asynchronous can interleave with running synchronous code. JavaScript's single thread is a guarantee, not a limitation, here.
  2. Microtasks drain completely. Both .then callbacks (C, D) run before any setTimeout, even though the timeouts were scheduled earlier. Priority beats scheduling order.
  3. Macrotasks go one per tick. B was enqueued during sync execution; E was enqueued while draining microtasks — so B precedes E.

The React Native tie-in that earns points: the bridge and InteractionManager live on this same loop — a long microtask chain (e.g. a .then that synchronously processes a huge JSON payload) starves timers and touch responsiveness exactly like a long sync block does.

Red flag: saying "setTimeout 0 runs immediately after the current line." It runs after sync code and after every pending microtask — and never sooner than the next tick.

Say it: "Sync runs to completion, the microtask queue drains fully, then one macrotask per tick — so promise callbacks always beat timers, and a microtask can starve the loop."