How the event loop works
- Execute all synchronous code (call stack)
- Drain the microtask queue completely (Promises,
queueMicrotask) - Pick one task from the macrotask queue (setTimeout, setInterval, I/O)
- Repeat from step 2
Promises
async/await
async/await is syntactic sugar over Promises. An async function always returns a Promise.
Microtasks vs macrotasks
| Queue | Examples | Priority |
|---|---|---|
| Microtask | Promise.then, queueMicrotask, MutationObserver | Higher — runs after every task |
| Macrotask | setTimeout, setInterval, I/O, requestAnimationFrame | Lower — one per loop iteration |
Common interview questions
What is the event loop?
What is the event loop?
The event loop is a mechanism that allows JavaScript to perform non-blocking operations despite being single-threaded. It continuously checks if the call stack is empty, then moves callbacks from the task queues to the stack for execution. Microtasks (Promises) are processed before macrotasks (setTimeout).
Why does setTimeout(fn, 0) not run immediately?
Why does setTimeout(fn, 0) not run immediately?
setTimeout(fn, 0) schedules fn as a macrotask. Even with 0ms delay, it won’t run until: (1) the current synchronous code finishes, and (2) all pending microtasks (Promises) are drained. The minimum delay in browsers is clamped to ~4ms.What is the difference between Promise.all and Promise.allSettled?
What is the difference between Promise.all and Promise.allSettled?
Promise.all— rejects immediately when any promise rejects. Useful when all results are required and one failure should abort the operation.Promise.allSettled— waits for all promises to settle (resolve or reject). Returns an array of{status, value/reason}objects. Useful when you need all results regardless of individual failures.
How do you handle errors in async/await?
How do you handle errors in async/await?
Wrap
await expressions in try/catch. For multiple independent awaits, each may need its own try/catch or you can use .catch() on individual promises. An unhandled rejection in an async function propagates as a rejected Promise from that function.