JavaScript Microtasks vs Macrotasks


What Are Microtasks and Macrotasks?

In JavaScript’s event loop model, tasks are categorized into Microtasks and Macrotasks (also called "Tasks"), which determine the order in which asynchronous code executes.

These queues help the browser decide what to run next when the call stack is empty.



Microtasks


What Are Microtasks?

Microtasks are tasks that are executed immediately after the current function execution and before any macrotask.


Common Microtask Sources:

  • Promise.then()
  • Promise.catch()
  • Promise.finally()
  • queueMicrotask()
  • MutationObserver (DOM changes observer)


Example:

console.log("Start");
Promise.resolve().then(() => {
console.log("Microtask");
});
console.log("End");

Output

Start
End
Microtask


Macrotasks (a.k.a. Tasks)


What Are Macrotasks?

Macrotasks are executed after the current stack and all microtasks are cleared.

Common Macrotask Sources:

  • setTimeout()
  • setInterval()
  • setImmediate() (Node.js)
  • requestAnimationFrame()
  • DOM events (like click, scroll)


Example:

console.log("Start");
setTimeout(() => {
console.log("Macrotask");
}, 0);
console.log("End");

Output

Start
End
Macrotask


Microtask vs Macrotask

Feature Microtask Macrotask
Priority Higher Lower
Executes after Current call stack Microtasks & current call stack
Examples Promise.then(), queueMicrotask() setTimeout(), setInterval()
Order FIFO (first-in, first-out) FIFO


Combined Example

console.log("Start");
setTimeout(() => {
console.log("Macrotask");
}, 0);
Promise.resolve().then(() => {
console.log("Microtask");
});
console.log("End");

Output

Start
End
Microtask
Macrotask


Why?

1. Start → executed immediately

2. End → executed immediately

3. Promise.then → goes to Microtask Queue

4. setTimeout → goes to Macrotask Queue

Microtasks always run before Macrotasks when the stack is clear.



Real-World Use

  • Promises for chaining logic (then, catch)
  • Timers to delay execution
  • Event handlers (clicks, keypresses)
  • Animation frames (requestAnimationFrame) for rendering