Window: queueMicrotask() method
ThequeueMicrotask()
method of theWindow
interfacequeues a microtask to be executed at a safe time prior to control returning to thebrowser's event loop.
The microtask is a short function which will run afterthe current task has completed its work and when there is no other code waiting to berun before control of the execution context is returned to the browser's event loop.
This lets your code run without interfering with any other, potentially higherpriority, code that is pending, but before the browser regains control over theexecution context, potentially depending on work you need to complete. You can learnmore about how to use microtasks and why you might choose to do so in ourmicrotask guide.
The importance of microtasks comes in its ability to perform tasks asynchronously butin a specific order. SeeUsing microtasks in JavaScript withqueueMicrotask()
for more details.
Microtasks are especially useful for libraries and frameworks that need to performfinal cleanup or other just-before-rendering tasks.
Syntax
queueMicrotask(callback)
Parameters
Return value
None (undefined
).
Examples
queueMicrotask(() => { // function contents here});
Taken from thequeueMicrotask spec:
MyElement.prototype.loadData = function (url) { if (this._cache[url]) { queueMicrotask(() => { this._setData(this._cache[url]); this.dispatchEvent(new Event("load")); }); } else { fetch(url) .then((res) => res.arrayBuffer()) .then((data) => { this._cache[url] = data; this._setData(data); this.dispatchEvent(new Event("load")); }); }};
Specifications
Specification |
---|
HTML # microtask-queuing |