JavaScript Microtasks

JavaScript Microtasks

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

PriorityTypeExamples
1️⃣ (High)MicrotasksPromise.then(), queueMicrotask(), MutationObserver
2️⃣ (Low)MacrotaskssetTimeout(), setInterval(), setImmediate() (Node.js), requestAnimationFrame()

✔ Microtasks run before any macrotask (even if the macrotask was scheduled first).

🔹 3. Example: Microtasks Execute Before setTimeout

console.log("🌟 Start"); setTimeout(() => console.log("⏳ setTimeout"), 0); Promise.resolve().then(() => console.log("✅ Promise 1")); Promise.resolve().then(() => console.log("✅ Promise 2")); console.log("🚀 End");

🛠 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.

console.log("🌟 Start"); queueMicrotask(() => console.log("🌀 Microtask 1")); queueMicrotask(() => console.log("🌀 Microtask 2")); console.log("🚀 End");

🛠 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.

let observer = new MutationObserver(() => { console.log("👀 DOM changed!"); }); let div = document.createElement("div"); document.body.appendChild(div); observer.observe(document.body, { childList: true }); div.textContent = "Hello, world!";

✔ 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.

console.log("🌟 Start"); Promise.resolve().then(() => { console.log("✅ Promise 1"); return Promise.resolve(); }).then(() => { console.log("✅ Promise 2"); }); console.log("🚀 End");

🛠 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

function infiniteMicrotasks() { Promise.resolve().then(infiniteMicrotasks); } infiniteMicrotasks(); // 🔥 Freezes browser!

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!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close