How does the event loop work? Microtasks vs macrotasks
MediumJavaScriptEvent loopAsync
How does the JavaScript event loop work, and what's the difference between microtasks and macrotasks?
TL;DR
JavaScript runs on a single thread with one call stack. Async work (timers, network, I/O) is handed to the browser or Node, and its callbacks wait in queues. The event loop repeats one cycle: run one macrotask, then drain all microtasks, then let the browser render if needed.
Microtasks (Promise callbacks, queueMicrotask, MutationObserver) always run before the next macrotask (setTimeout, setInterval, I/O, UI events).
Key points
- The call stack must be empty before any queued callback runs.
- The whole microtask queue is drained each cycle, including microtasks added while draining.
setTimeout(fn, 0)means "at least 0 ms, after current work and all microtasks", not "now".- Rendering happens between macrotasks, so long synchronous work or endless microtasks freeze the UI.
awaitsplits a function: everything after it runs as a microtask.
Example
js
console.log('1')
setTimeout(() => console.log('2'), 0)
Promise.resolve().then(() => console.log('3'))
console.log('4')
// 1, 4, 3, 21 and 4 are synchronous. 3 is a microtask, so it runs before the setTimeout macrotask 2.
Common follow-ups
- How do you keep a long task from blocking the UI? Split it into chunks with
setTimeoutorscheduler.yield(), or move it to a Web Worker. - Where does
requestAnimationFramerun? Right before the browser paints, once per frame. It's the right place for visual updates.
What interviewers look for
Tip
Predict the output order correctly and explain why: sync code, then all microtasks, then the next macrotask.
- Red flag: thinking
setTimeout(fn, 0)runs immediately, or that JavaScript runs callbacks in parallel threads.