What is the difference between microtasks and macrotasks
· Category: JavaScript
Short answer
Macrotasks include setTimeout, setInterval, and I/O callbacks. Microtasks include Promise callbacks and queueMicrotask. The event loop drains the microtask queue before the next macrotask.
How it works
- Execute one macrotask from the queue.
- Execute all microtasks that were queued during that macrotask.
- Render the UI if needed.
- Repeat.
Example
setTimeout(() => console.log("macrotask"), 0);
Promise.resolve().then(() => console.log("microtask"));
console.log("synchronous");
// Output: synchronous, microtask, macrotask
Why it matters
Heavy microtask scheduling can starve macrotasks and block rendering. Use setTimeout(..., 0) to yield control back to the browser, and queueMicrotask for work that should run before the next render or macrotask.