queueMicrotask Ordering Against Promises And Timers
Schedule callbacks with queueMicrotask and observe that microtasks run in enqueue order after synchronous code but before setTimeout timers get their turn.
Code
// queueMicrotask: 排进微任务队列——同步代码之后、定时器之前执行
const order = [];
setTimeout(() => order.push('timeout-0'), 0);
Promise.resolve().then(() => order.push('promise-then'));
queueMicrotask(() => order.push('queueMicrotask'));
console.log('sync first');
setTimeout(() => {
// 微任务按入队顺序清空后,才会执行宏任务
console.log(order.join(' -> '));
}, 0);Output
Captured from a sandboxed run of this snippet in the build pipeline.
sync first
promise-then -> queueMicrotask -> timeout-0How it works
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Top-level bindings order hold the demo state — nothing sits inside a function scope.
Putting it to use
The demo output is labeled (sync first), so every printed line maps back to its originating operation.
Core lines
Promise.resolve().then(() => order.push('promise-then'));
queueMicrotask(() => order.push('queueMicrotask'));
setTimeout(() => order.push('timeout-0'), 0);
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `order`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.