Study notes · 10% of the exam

The Event Loop and Timers

JavaScript runs one task at a time on a single thread. Know how tasks, microtasks, rendering and Node's loop phases interleave, and you can predict any output-order puzzle and spot code that freezes a page or a server.

Key points

  1. 1

    Run to completion: once a task starts, nothing else on that thread runs until the call stack is empty. Timers and events wait their turn; they never interrupt.

  2. 2

    After every task, and after every callback that returns to an empty stack, the microtask queue is drained completely, including microtasks queued during the drain. Promise reactions, await continuations, queueMicrotask and MutationObserver notifications are microtasks.

  3. 3

    Rendering (rAF callbacks, style, layout, paint) happens only between tasks. Splitting work into separate tasks (setTimeout, MessageChannel, scheduler.yield) lets the page paint and respond; splitting it into microtasks does not.

  4. 4

    Awaiting a native promise costs one tick, a thenable costs one more, and returning a promise from an async function costs two extra ticks before its result settles.

  5. 5

    Node runs timers → pending → poll → check (setImmediate) → close each iteration. After each callback it drains process.nextTick, then promise microtasks. Inside an I/O callback, setImmediate always beats setTimeout(0); in the main module the order varies.

  6. 6

    Async fs, dns.lookup, crypto and zlib work runs on libuv's thread pool (4 threads by default, UV_THREADPOOL_SIZE). Network sockets use the OS's non-blocking I/O instead.

Common traps

  • A real user click runs a microtask checkpoint between listeners; element.click() from a script does not, so microtask ordering differs in tests.

  • Delays are minimums: nested timers are clamped to 4 ms, and background tabs throttle timers to about once per second and pause rAF.

  • await Promise.resolve() in a long loop does not yield to I/O or rendering; await a macrotask (setImmediate, setTimeout) instead.

Test yourself on The Event Loop and Timers

Ten questions, with the answer and explanation after each one.