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:
- Macrotask Queue
- 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);
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");
});
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");
β Output
Start
End
Microtask
Macrotask
π€ Why This Happens
Execution order:
- Synchronous code runs first
- Microtasks run completely
- Then one Macrotask runs
- 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:
- Synchronous code
- Microtasks
- Macrotasks
If interviewer asks:
βWhich runs first, Promise or setTimeout?β
Answer:
Promise (Microtask) runs first.
Top comments (0)