JavaScript Macro and Micro Task Execution Explanation
JavaScript has a single-threaded event loop, meaning it processes one task at a time. However, within this loop, tasks are divided into macro-tasks and micro-tasks, which determine the execution order.
1. Macro-tasks vs. Micro-tasks
🔹 Macro-tasks (Task Queue)
Macro-tasks include:
setTimeout
setInterval
setImmediate
(Node.js only)I/O operations (e.g., file reading, network requests)
UI rendering tasks
🔹 Micro-tasks (Microtask Queue)
Micro-tasks include:
Promises (
.then
,.catch
,.finally
)MutationObserver
process.nextTick (Node.js only)
2. Execution Order:
JavaScript executes synchronous code first.
It processes all micro-tasks in the queue before moving to the next macro-task.
The event loop picks one macro-task from the queue and executes it.
After executing the macro-task, it checks and executes all pending micro-tasks.
Steps 3 and 4 repeat.
3. Example:
javascriptCopyEditconsole.log("1"); // Synchronous
setTimeout(() => {
console.log("2"); // Macro-task
}, 0);
Promise.resolve().then(() => {
console.log("3"); // Micro-task
});
console.log("4"); // Synchronous
Execution Order:
1️⃣ "1"
→ Synchronous
2️⃣ "4"
→ Synchronous
3️⃣ "3"
→ Micro-task (Promise resolves before macro-task)
4️⃣ "2"
→ Macro-task (setTimeout executes last)
🔹 Output:
CopyEdit1
4
3
2
4. Another Example with Nested Tasks:
javascriptCopyEditconsole.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
Promise.resolve().then(() => {
console.log("Promise 1");
}).then(() => {
console.log("Promise 2");
});
console.log("End");
Execution Order:
1️⃣ "Start"
→ Synchronous
2️⃣ "End"
→ Synchronous
3️⃣ "Promise 1"
→ Micro-task
4️⃣ "Promise 2"
→ Micro-task
5️⃣ "Timeout"
→ Macro-task
🔹 Output:
javascriptCopyEditStart
End
Promise 1
Promise 2
Timeout
5. Key Takeaways
✅ Micro-tasks always execute before macro-tasks after the synchronous code runs.
✅ Promises (micro-tasks) resolve before setTimeout
(macro-tasks).
✅ Multiple micro-tasks are executed in order before moving to the next macro-task.
Would you like a more complex example or a real-world use case? 🚀