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

  1. Execute one macrotask from the queue.
  2. Execute all microtasks that were queued during that macrotask.
  3. Render the UI if needed.
  4. 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.