javascript / intermediate
Snippet
Prioritizing with queueMicrotask
The queueMicrotask() method allows you to queue a function to be executed after the current task finishes but before the event loop continues. It has higher priority than Macrotasks like setTimeout.
snippet.js
1
2
3
4
console.log('Sync');setTimeout(() => console.log('Timeout'), 0);queueMicrotask(() => console.log('Microtask'));console.log('End');
Breakdown
1
setTimeout(() => ..., 0);
Schedules a Macrotask to run in the next iteration of the event loop.
2
queueMicrotask(() => ...);
Schedules a Microtask to run immediately after the current script execution.
3
console.log('End');
Runs synchronously before any queued tasks.