Skip to content

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.

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 an await) and queueMicrotask.
  • 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, timeout

setTimeout(fn, 0) does not mean “now”. It means “as a macrotask, after the current stack and all microtasks are done”.

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.

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.

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.

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 await are microtasks. Timers and I/O are macrotasks.
  • An async function runs synchronously up to its first await.
  • 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.