The event loop
Relay’s worker parses a batch of 5,000 webhook bodies. The loop is plain synchronous code, and it takes two seconds. For those two seconds the health check does not answer, no new request is read, and a timer that should fire at 500 ms fires at 2,000 ms. The orchestrator sees a dead process and restarts it.
JavaScript runs one thing at a time. To find the bug you need the exact order in which the engine picks the next thing to run. This lesson gives you that order, then builds a helper that lets other work in between the items of a batch.
One stack, two queues
Section titled “One stack, two queues”The engine runs code until the call stack is empty. Only then does it look at its queues:
- Microtasks: promise reactions (
.then, the code after anawait) andqueueMicrotask. - Macrotasks: timers (
setTimeout), I/O completions, incoming messages.
The rule: after each piece of running code finishes, run every microtask, including ones the microtasks add, and only then take one macrotask. A microtask never waits for a timer.
const log: string[] = []log.push("start")setTimeout(() => log.push("timeout"), 0)Promise.resolve().then(() => log.push("promise"))queueMicrotask(() => log.push("microtask"))log.push("end")// once everything has run: start, end, promise, microtask, timeoutsetTimeout(fn, 0) does not mean “now”. It means “as a macrotask, after the current stack and all
microtasks are done”.
await ordering
Section titled “await ordering”An async function runs synchronously until its first await. Everything after the await is a
microtask. So the caller gets control back before the rest of the function runs:
async function demo(): Promise<string[]> { const log: string[] = [] async function f() { log.push("f1") await null log.push("f2") } const p = f() log.push("after f()") await p return log // f1, after f(), f2}Two promise chains started in the same tick take turns, one step each: a1, b1, a2, b2. A chain
does not run to its end before the other one starts.
Why a sync loop blocks everything
Section titled “Why a sync loop blocks everything”Timers and I/O are macrotasks. They get a turn only when the stack is empty and the microtask queue
is drained. A for loop over 5,000 items never empties the stack, so none of them run:
declare function parseBody(raw: string): unknown
function parseBatch(bodies: readonly string[]): unknown[] { const out: unknown[] = [] for (const body of bodies) out.push(parseBody(body)) // 5,000 iterations, nothing else runs return out}The same goes for a loop that only does await on already-resolved promises. Each await is a
microtask, microtasks are drained before any macrotask, so the timers still starve.
Yielding to the loop
Section titled “Yielding to the loop”To let timers and I/O in, wait for a macrotask. setTimeout(resolve, 0) is the portable way:
const macrotask = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
async function parseBatch<T>(bodies: readonly string[], parse: (raw: string) => T): Promise<T[]> { const out: T[] = [] for (const [i, body] of bodies.entries()) { out.push(parse(body)) if (i % 100 === 99) await macrotask() // let timers and requests run every 100 items } return out}Yielding on every item is wasteful, since each yield costs a trip through the loop. Yielding every n items keeps the pause between turns short without paying for it each time.
Exercise
Section titled “Exercise”Four snippets, each logging as it goes. In predictions, write the log each one produces. The tests
run the snippets for real, so a wrong guess shows the real order. Then write yieldEvery and
processAll: after every every items, processAll must let a waiting timer run.
- One stack. After it empties, all microtasks run, then one macrotask.
- Promise reactions and code after
awaitare microtasks. Timers and I/O are macrotasks. - An
asyncfunction runs synchronously up to its firstawait. - A sync loop, or a loop of resolved awaits, starves timers and I/O. Yield with a macrotask every n items, not on every item.
- Real waiting is a later topic: see promises and async for timeouts, and cancellation for stopping work.
Further reading
Section titled “Further reading”- JavaScript execution model (MDN): the call stack, job queue and event loop, in plain terms.
- Event loops (HTML Standard): the exact rules for tasks and microtasks.