JavaScript Microtasks
Microtasks are a special type of task in JavaScript that execute immediately after the currently executing script and before any other tasks (like timers or rendering updates).
They are mainly used in Promises and MutationObservers.
🔹 1. What are Microtasks?
Microtasks are high-priority asynchronous tasks that execute before any other asynchronous tasks (like setTimeout
or setInterval
).
🔹 Examples of Microtasks:
✔ Promise callbacks (.then()
, .catch()
, .finally()
)
✔ MutationObserver (listens to DOM changes)
✔ queueMicrotask() (explicitly schedules a microtask)
🔹 2. Microtasks vs Macrotasks
JavaScript has two main types of asynchronous tasks:
1️⃣ Microtasks (high priority, executes ASAP)
2️⃣ Macrotasks (low priority, executes after rendering and UI updates)
📌 Execution Order
Priority | Type | Examples |
---|---|---|
1️⃣ (High) | Microtasks | Promise.then() , queueMicrotask() , MutationObserver |
2️⃣ (Low) | Macrotasks | setTimeout() , setInterval() , setImmediate() (Node.js), requestAnimationFrame() |
✔ Microtasks run before any macrotask (even if the macrotask was scheduled first).
🔹 3. Example: Microtasks Execute Before setTimeout
🛠 Execution Order:
1️⃣ "🌟 Start"
(synchronous)
2️⃣ "🚀 End"
(synchronous)
3️⃣ "✅ Promise 1"
(microtask)
4️⃣ "✅ Promise 2"
(microtask)
5️⃣ "⏳ setTimeout"
(macrotask)
🔹 Even though setTimeout()
is scheduled first, Promises execute first!
🔹 4. queueMicrotask()
- Manually Schedule a Microtask
JavaScript provides queueMicrotask()
to manually queue a microtask.
🛠 Execution Order:
1️⃣ "🌟 Start"
2️⃣ "🚀 End"
3️⃣ "🌀 Microtask 1"
4️⃣ "🌀 Microtask 2"
🔹 Microtasks execute immediately after the main script, before any rendering or timers.
🔹 5. Using Microtasks with MutationObserver
MutationObserver
is a built-in browser API that detects changes in the DOM and executes a microtask.
✔ The callback runs as a microtask, executing before timers and rendering.
🔹 6. Microtask Queue Keeps Running Until Empty
If a microtask adds another microtask, the event loop will continue executing microtasks before moving to macrotasks.
🛠 Execution Order:
1️⃣ "🌟 Start"
2️⃣ "🚀 End"
3️⃣ "✅ Promise 1"
(microtask)
4️⃣ "✅ Promise 2"
(microtask, added by first microtask)
🔹 JavaScript will process all microtasks before moving on!
🔹 7. How Microtasks Affect Performance
✔ Microtasks are fast and ensure smooth UI updates.
✔ Too many microtasks can block rendering if they keep adding more tasks.
🛑 Bad Example: Infinite Microtask Loop
⏳ Problem: Since each microtask schedules another microtask, it never moves to macrotasks or rendering.
🔹 8. Summary
✔ Microtasks run before macrotasks
✔ Promises and queueMicrotask()
are microtasks
✔ Microtask queue runs until empty before moving to the next macrotask
✔ Too many microtasks can block UI rendering
🚀 Microtasks make JavaScript fast and efficient!