In the early days of JavaScript, there was only one queue (the Callback Queue). With the introduction of Promises, the architecture changed. We now have two distinct waiting areas for asynchronous callbacks.
This is the standard queue we discussed in previous unit.
setTimeout, setInterval, setImmediate (Node), I/O tasks, UI Rendering.This is a high-priority queue introduced specifically for Promises.
Promise.then, .catch, .finally, queueMicrotask, MutationObserver.The Golden Algorithm:
Key Takeaway: The Microtask Queue must be completely empty before the Event Loop will even look at the Macrotask Queue.
Let's predict the output of mixed synchronous and asynchronous code.
console.log("1. Script Start");
// Macrotask
setTimeout(() => {
console.log("2. setTimeout");
}, 0);
// Microtask
Promise.resolve().then(() => {
console.log("3. Promise 1");
});
// Microtask
Promise.resolve().then(() => {
console.log("4. Promise 2");
});
console.log("5. Script End");1. Script Start
5. Script End
3. Promise 1
4. Promise 2
2. setTimeoutBecause the Event Loop flushes the entire Microtask Queue before moving on, it is possible to block the Macrotask Queue indefinitely.
If a Microtask adds another Microtask, which adds another Microtask, the engine will be stuck in Microtask queue forever.
function infiniteMicrotasks() {
Promise.resolve().then(() => {
console.log("I am blocking the macrotask queue!");
infiniteMicrotasks(); // Adds a new microtask immediately
});
}
infiniteMicrotasks();
// Result: The page freezes. Click events (Macrotasks) never run.| Feature | Macrotask (Task Queue) | Microtask (Job Queue) |
|---|---|---|
| Examples | setTimeout, setInterval, DOM Events | Promise.then, queueMicrotask |
| Priority | Low | High |
| Execution Policy | Run ONE, then check Microtasks | Run ALL until empty |
| Danger | Safe (allows UI rendering between tasks) | Can starve the Event Loop (block UI) |
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("Sync");Answer:
1. Sync (Stack)
2. Promise (Microtask - Priority)
3. Timeout (Macrotask - Last)