One thread, many jobs
The browser runs your JavaScript on a single main thread. The event loop decides what runs next so the page stays responsive.
Tasks and microtasks
- A task (macrotask) is a unit of work like a click handler, a timer callback, or a network event.
- A microtask is queued by promises and queueMicrotask.
- After each task, the loop drains the entire microtask queue before rendering.
This is why a resolved promise callback runs before a setTimeout of zero.
Rendering opportunities
Between tasks the browser may run requestAnimationFrame callbacks and then paint. Long tasks block this, so heavy synchronous work freezes the UI.
- Break work into smaller chunks.
- Offload computation to a Web Worker.
Key idea
Microtasks always finish before the next render, so promises resolve ahead of timers and long tasks block painting.