DEV Community

Shashi Bhushan Kumar
Shashi Bhushan Kumar

Posted on

Microtask vs Macrotask Explained Simply

Microtask vs Macrotask Explained Simply

After understanding the Event Loop,

there is one more important concept:

πŸ‘‰ Microtask vs Macrotask

This is a very common interview question.

Let’s understand it in the simplest way possible.


First Understand This

When asynchronous tasks finish,

they don’t directly go to the Call Stack.

They go into queues.

But there are TWO types of queues:

  1. Macrotask Queue
  2. Microtask Queue

πŸ“¦ What is a Macrotask?

Macrotasks are normal async tasks like:

  • setTimeout
  • setInterval
  • setImmediate (Node.js)
  • DOM events

Example:

setTimeout(() => {
  console.log("Macrotask");
}, 0);
Enter fullscreen mode Exit fullscreen mode

setTimeout always goes to the Macrotask Queue.


⚑ What is a Microtask?

Microtasks are higher priority tasks like:

  • Promises (.then, .catch)
  • async/await
  • queueMicrotask

Example:

Promise.resolve().then(() => {
  console.log("Microtask");
});
Enter fullscreen mode Exit fullscreen mode

Promises go to the Microtask Queue.


πŸƒβ€β™‚οΈ Which Runs First?

πŸ‘‰ Microtasks ALWAYS run before Macrotasks.

Even if setTimeout has 0 delay.


πŸ’» Example

console.log("Start");

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

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

console.log("End");
Enter fullscreen mode Exit fullscreen mode

βœ… Output

Start
End
Microtask
Macrotask
Enter fullscreen mode Exit fullscreen mode

πŸ€” Why This Happens

Execution order:

  1. Synchronous code runs first
  2. Microtasks run completely
  3. Then one Macrotask runs
  4. Again microtasks are checked

Microtasks have higher priority.


🍽 Real-Life Example

Imagine:

Macrotasks = normal customers

Microtasks = VIP customers

Restaurant rule:

  • Finish all VIP customers first
  • Then serve normal customers

That’s exactly how JavaScript behaves.


🎯 Important Interview Point

Priority order:

  1. Synchronous code
  2. Microtasks
  3. Macrotasks

If interviewer asks:

β€œWhich runs first, Promise or setTimeout?”

Answer:
Promise (Microtask) runs first.

Top comments (0)