Async JavaScript
Event Loop, Microtasks & Macrotasks
JavaScript executes synchronous code on a call stack and uses an event loop to resume queued work later. Promise reactions run as microtasks, which are drained before the next task such as a timer or event callback.
- JavaScript execution is run-to-completion
- The call stack must empty before queued work runs
- Microtasks run before the next task
- Long synchronous work blocks everything
- Node and browsers have host-specific details
console.log("A")
setTimeout(() => console.log("timer"), 0)
Promise.resolve().then(() => console.log("promise"))
console.log("B")
// A
// B
// promise
// timer| Thing | Examples | When it runs |
|---|---|---|
| Call stack | Current synchronous function | Immediately |
| Microtask | Promise reactions, queueMicrotask | After stack clears, before next task |
| Task | Timers, events, I/O callbacks | One per event-loop turn |
| Rendering | Browser paint/layout | Between turns, host-specific |