queueMicrotask
Queues a function as a microtask — it runs before any timer.
Available since: Web API
Syntax
queueMicrotask(callback)Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | Function | A function that runs right after the current code. |
Return value
undefinedReturns nothing.
Examples
The order of execution:
setTimeout(() => console.log('timeout'), 0);
queueMicrotask(() => console.log('microtask'));
Promise.resolve().then(() => console.log('promise'));
console.log('sync');Output:
sync
microtask
promise
timeoutNotes
First all synchronous code runs, then all microtasks (promise handlers and queueMicrotask) in order, and only then timers.
See also
- setTimeout — Runs a function once after a delay.
- Promise.prototype.then — Says what to do with a promise's result.
In the tutorial
- The event loop — How JavaScript runs code: synchronous and asynchronous code, the task queue, microtasks and the event loop.