Careeroza
Call Stack and Web APIs
One Thread
JavaScript runs on a single thread with one call stack. Slow work like timers and network requests is handed to the browser (Web APIs) or to Node's libuv. When that work finishes, its callback waits in a queue. The event loop moves callbacks from the queues to the stack when the stack is empty.
┌─────────────┐ ┌──────────────────────┐
│ Call Stack │ ──► │ Web APIs / libuv │ setTimeout, fetch, DOM events
└─────────────┘ └──────────┬───────────┘
▲ ▼
│ ┌──────────────────────┐
│ │ Microtask queue │ promise callbacks, queueMicrotask
│ ├──────────────────────┤
└─ event ────│ Macrotask (task) queue│ setTimeout, setInterval, I/O, events
loop └──────────────────────┘The Loop
- Run all synchronous code until the call stack is empty.
- Run all microtasks (including microtasks added while running them).
- Browser may render (paint) the page.
- Take one macrotask from the task queue and run it; then go back to step 2.