--- title: WindowOrWorkerGlobalScope.queueMicrotask() slug: Web/API/queueMicrotask tags: - API - JavaScript - Method - Microtask - 参考 - 同步 - 方法 translation_of: Web/API/WindowOrWorkerGlobalScope/queueMicrotask original_slug: Web/API/WindowOrWorkerGlobalScope/queueMicrotask ---
queueMicrotask()
方法,queues a microtask to be executed at a safe time prior to control returning to the browser's event loop.microtask 是一个简短的函数,它将在当前任务(task)完成其工作之后运行,并且在执行上下文的控制返回到浏览器的事件循环之前,没有其他代码等待运行。The microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run 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 higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. You can learn more about how to use microtasks and why you might choose to do so in our microtask guide.
The importance of microtasks comes in its ability to perform tasks asynchronously but in a specific order. See Using microtasks in JavaScript with queueMicrotask() for more details.
Microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks.
queueMicrotask()
处于 {{domxref("WindowOrWorkerGlobalScope")}} mixin 之下。
scope.queueMicrotask(function);
function
undefined
。
self.queueMicrotask(() => { // 函数的内容 })
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")); }); } };
下面的代码是一份 queueMicrotask()
的 polyfill。它通过使用立即 resolve 的 promise 创建一个微任务(microtask),如果无法创建 promise,则回落(fallback)到使用setTimeout()
。
if (typeof window.queueMicrotask !== "function") { window.queueMicrotask = function (callback) { Promise.resolve() .then(callback) .catch(e => setTimeout(() => { throw e; })); }; }
Specification | Status | Comment |
---|---|---|
{{SpecName("HTML WHATWG", "timers-and-user-prompts.html#microtask-queuing", "self.queueMicrotask()")}} | {{Spec2("HTML WHATWG")}} | Initial definition |
{{Compat("api.WindowOrWorkerGlobalScope.queueMicrotask")}}