Consistent deferred notifications
A library needs to normalize synchronous and asynchronous completion so observers are notified consistently after the current operation.
JavaScript · Function
queueMicrotask() schedules a function as a microtask. The function runs after the current task completes, before control returns to the event loop.
Calling queueMicrotask(callback) places callback in the microtask queue. After the current task finishes and the JavaScript stack is empty, the runtime drains pending microtasks before yielding back to the event loop; callbacks added while draining run in that same draining phase.
queueMicrotask(callback)| Name | Type | Description |
|---|---|---|
callback | Function | A function invoked when the runtime determines that it is safe to execute the callback. |
undefined
const order = [];
order.push("task");
queueMicrotask(() => order.push("microtask"));
order.push("after scheduling");
setTimeout(() => {
console.log(order);
}, 0);The scheduled callback runs after the current synchronous code finishes, so the output is ["task", "after scheduling", "microtask"].
A library needs to normalize synchronous and asynchronous completion so observers are notified consistently after the current operation.
A framework or component needs final cleanup or work immediately before rendering.
Code must preserve the order of short asynchronous follow-up operations without waiting for a later task.
queueMicrotask(callback) schedules callback for the microtask queue. It runs after the current task completes and before control returns to the event loop.
Follow-up: How does it compare with setTimeout(..., 0)? setTimeout schedules a later task, while a queued microtask is drained before the next task begins.
The function takes one callback parameter, which is invoked when the runtime determines it is safe to run the code. The method itself returns undefined.
Follow-up: What happens if the callback queues another microtask? The newly queued microtask runs before the next task because microtask processing continues until the queue is empty.
Microtasks provide asynchronous execution with deterministic ordering. They are useful when code must run after the current operation but before the browser regains control, including library cleanup or just-before-rendering work.
Follow-up: Why can recursive scheduling be harmful? Since newly added microtasks are processed before the next task, continuous scheduling can postpone tasks and rendering.
Window.queueMicrotask()WorkerGlobalScope.queueMicrotask()setTimeout()Promise