What Goes in the Microtask Queue
You'll learn which specific JavaScript operations use the microtask queue instead of the regular task queue.
The Microtask Queue's Special Residents
In the previous lesson, you learned that JavaScript has two queues: tasks and microtasks. Now let's identify exactly what goes into the microtask queue.
Three primary sources feed the microtask queue:
1. Promise Callbacks
When a promise settles (resolves or rejects), its .then(), .catch(), or .finally() callbacks are queued as microtasks:
Promise.resolve().then(() => {
console.log('This is a microtask');
});
This is why promise callbacks run before other asynchronous operations like setTimeout, even if the timeout is set to zero.
2. queueMicrotask()
JavaScript provides a direct way to schedule microtasks using the global queueMicrotask() function:
queueMicrotask(() => {
console.log('Directly queued microtask');
});
This gives you explicit control over microtask timing without needing promises.
3. MutationObserver Callbacks
When using the MutationObserver API to watch for DOM changes, the callbacks fire as microtasks. This ensures they run quickly after DOM modifications but before rendering.
Think of It This Way
Imagine the microtask queue as the "VIP lane" at an airport. Only three types of passengers get VIP access: promise handlers, explicitly VIP-ticketed travelers (queueMicrotask), and DOM watchers (MutationObserver). Everyone else waits in the regular line (task queue).
Key Takeaway: Promise callbacks, queueMicrotask(), and MutationObserver callbacks all use the microtask queue, giving them priority execution after the current script completes but before tasks from the task queue run.