From b4ad1ea1eafb89fb4cdecd1a5ac092ab47cb4e82 Mon Sep 17 00:00:00 2001 From: skyclouds2001 <95597335+skyclouds2001@users.noreply.github.com> Date: Wed, 18 Sep 2024 06:10:56 +0000 Subject: [PATCH 1/2] move --- files/en-us/_redirects.txt | 3 ++- files/en-us/_wikihistory.json | 20 +++++++++---------- .../api/{ => window}/queuemicrotask/index.md | 2 +- .../javascript/guide/using_promises/index.md | 2 +- .../reference/operators/await/index.md | 2 +- 5 files changed, 15 insertions(+), 14 deletions(-) rename files/en-us/web/api/{ => window}/queuemicrotask/index.md (98%) diff --git a/files/en-us/_redirects.txt b/files/en-us/_redirects.txt index b587e9a63a476e3..8c93c9228fd5969 100644 --- a/files/en-us/_redirects.txt +++ b/files/en-us/_redirects.txt @@ -10262,7 +10262,7 @@ /en-US/docs/Web/API/WindowOrWorkerGlobalScope/indexedDB /en-US/docs/Web/API/Window/indexedDB /en-US/docs/Web/API/WindowOrWorkerGlobalScope/isSecureContext /en-US/docs/Web/API/Window/isSecureContext /en-US/docs/Web/API/WindowOrWorkerGlobalScope/origin /en-US/docs/Web/API/Window/origin -/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask /en-US/docs/Web/API/queueMicrotask +/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask /en-US/docs/Web/API/Window/queueMicrotask /en-US/docs/Web/API/WindowOrWorkerGlobalScope/rejectionhandled_event /en-US/docs/Web/API/Window/rejectionhandled_event /en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval /en-US/docs/Web/API/setInterval /en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout /en-US/docs/Web/API/setTimeout @@ -10709,6 +10709,7 @@ /en-US/docs/Web/API/onMSVideoOptimalLayoutChanged_ /en-US/docs/Web/API/HTMLVideoElement /en-US/docs/Web/API/origin /en-US/docs/Web/API/Window/origin /en-US/docs/Web/API/performance_property /en-US/docs/Web/API/Window/performance +/en-US/docs/Web/API/queueMicrotask /en-US/docs/Web/API/Window/queueMicrotask /en-US/docs/Web/API/range.cloneContents /en-US/docs/Web/API/range/cloneContents /en-US/docs/Web/API/range.cloneRange /en-US/docs/Web/API/range/cloneRange /en-US/docs/Web/API/range.collapse /en-US/docs/Web/API/range/collapse diff --git a/files/en-us/_wikihistory.json b/files/en-us/_wikihistory.json index 9d074f9ae90e53a..1eded3927d96729 100644 --- a/files/en-us/_wikihistory.json +++ b/files/en-us/_wikihistory.json @@ -68208,6 +68208,16 @@ "JesseW" ] }, + "Web/API/Window/queueMicrotask": { + "modified": "2020-10-15T22:21:06.789Z", + "contributors": [ + "Kaiido", + "chrisdavidmills", + "Sheppy", + "zbjornson", + "DomenicDenicola" + ] + }, "Web/API/Window/rejectionhandled_event": { "modified": "2020-10-15T21:44:33.123Z", "contributors": [ @@ -71518,16 +71528,6 @@ "adria" ] }, - "Web/API/queueMicrotask": { - "modified": "2020-10-15T22:21:06.789Z", - "contributors": [ - "Kaiido", - "chrisdavidmills", - "Sheppy", - "zbjornson", - "DomenicDenicola" - ] - }, "Web/API/setInterval": { "modified": "2020-12-09T23:19:41.310Z", "contributors": [ diff --git a/files/en-us/web/api/queuemicrotask/index.md b/files/en-us/web/api/window/queuemicrotask/index.md similarity index 98% rename from files/en-us/web/api/queuemicrotask/index.md rename to files/en-us/web/api/window/queuemicrotask/index.md index 0d05abbf5e36c18..db9f93addddeddd 100644 --- a/files/en-us/web/api/queuemicrotask/index.md +++ b/files/en-us/web/api/window/queuemicrotask/index.md @@ -1,7 +1,7 @@ --- title: queueMicrotask() global function short-title: queueMicrotask() -slug: Web/API/queueMicrotask +slug: Web/API/Window/queueMicrotask page-type: web-api-global-function browser-compat: api.queueMicrotask --- diff --git a/files/en-us/web/javascript/guide/using_promises/index.md b/files/en-us/web/javascript/guide/using_promises/index.md index 73f53f2d0060aa5..673f62518af8ac7 100644 --- a/files/en-us/web/javascript/guide/using_promises/index.md +++ b/files/en-us/web/javascript/guide/using_promises/index.md @@ -542,7 +542,7 @@ For more details, refer to [Tasks vs. microtasks](/en-US/docs/Web/API/HTML_DOM_A If you run into situations in which you have promises and tasks (such as events or callbacks) which are firing in unpredictable orders, it's possible you may benefit from using a microtask to check status or balance out your promises when promises are created conditionally. -If you think microtasks may help solve this problem, see the [microtask guide](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) to learn more about how to use [`queueMicrotask()`](/en-US/docs/Web/API/queueMicrotask) to enqueue a function as a microtask. +If you think microtasks may help solve this problem, see the [microtask guide](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) to learn more about how to use [`queueMicrotask()`](/en-US/docs/Web/API/Window/queueMicrotask) to enqueue a function as a microtask. ## See also diff --git a/files/en-us/web/javascript/reference/operators/await/index.md b/files/en-us/web/javascript/reference/operators/await/index.md index d090cb60543e23e..7ad0194e77ffeaf 100644 --- a/files/en-us/web/javascript/reference/operators/await/index.md +++ b/files/en-us/web/javascript/reference/operators/await/index.md @@ -237,7 +237,7 @@ function foo(name) { While the extra `then()` handler is not necessary, and the handler can be merged with the executor passed to the constructor, the `then()` handler's existence means the code will take one extra tick to complete. The same happens for `await`. Therefore, make sure to use `await` only when necessary (to unwrap promises into their values). -Other microtasks can execute before the async function resumes. This example uses [`queueMicrotask()`](/en-US/docs/Web/API/queueMicrotask) to demonstrate how the microtask queue is processed when each `await` expression is encountered. +Other microtasks can execute before the async function resumes. This example uses [`queueMicrotask()`](/en-US/docs/Web/API/Window/queueMicrotask) to demonstrate how the microtask queue is processed when each `await` expression is encountered. ```js let i = 0; From 107883ec69ba4a912b10a42e91ec5b09bab25325 Mon Sep 17 00:00:00 2001 From: skyclouds2001 <95597335+skyclouds2001@users.noreply.github.com> Date: Wed, 18 Sep 2024 15:39:13 +0800 Subject: [PATCH 2/2] update --- .../mozilla/firefox/releases/69/index.md | 2 +- .../microtask_guide/in_depth/index.md | 6 +- .../api/html_dom_api/microtask_guide/index.md | 12 +-- files/en-us/web/api/settimeout/index.md | 5 +- .../index.md | 4 +- files/en-us/web/api/web_workers_api/index.md | 4 +- files/en-us/web/api/window/index.md | 2 +- .../web/api/window/queuemicrotask/index.md | 16 ++-- .../en-us/web/api/workerglobalscope/index.md | 2 +- .../workerglobalscope/queuemicrotask/index.md | 91 +++++++++++++++++++ .../javascript/guide/using_promises/index.md | 2 +- .../reference/operators/await/index.md | 2 +- 12 files changed, 120 insertions(+), 28 deletions(-) create mode 100644 files/en-us/web/api/workerglobalscope/queuemicrotask/index.md diff --git a/files/en-us/mozilla/firefox/releases/69/index.md b/files/en-us/mozilla/firefox/releases/69/index.md index 59e9a47290996b4..ff62c309f20365a 100644 --- a/files/en-us/mozilla/firefox/releases/69/index.md +++ b/files/en-us/mozilla/firefox/releases/69/index.md @@ -84,7 +84,7 @@ This article provides information about the changes in Firefox 69 that will affe #### New APIs - The [Resize Observer API](/en-US/docs/Web/API/Resize_Observer_API) is supported by default ([Firefox bug 1543839](https://bugzil.la/1543839)). -- The Microtask API ({{domxref("queueMicrotask()")}}) has been implemented ([Firefox bug 1480236](https://bugzil.la/1480236)). +- The Microtask API ({{domxref("Window.queueMicrotask()")}} and {{domxref("WorkerGlobalScope.queueMicrotask()")}}) has been implemented ([Firefox bug 1480236](https://bugzil.la/1480236)). #### DOM diff --git a/files/en-us/web/api/html_dom_api/microtask_guide/in_depth/index.md b/files/en-us/web/api/html_dom_api/microtask_guide/in_depth/index.md index a6a6a5ecbddf975..514229521a77a50 100644 --- a/files/en-us/web/api/html_dom_api/microtask_guide/in_depth/index.md +++ b/files/en-us/web/api/html_dom_api/microtask_guide/in_depth/index.md @@ -12,7 +12,7 @@ JavaScript is an inherently single-threaded language. It was designed in an era As time passed, of course, we know that computers have evolved into powerful multi-core systems, and JavaScript has become one of the most prolifically-used languages in the computing world. A vast number of the most popular applications are based at least in part on JavaScript code. To support this, it was necessary to find ways to allow for projects to escape the limitations of a single-threaded language. -Starting with the addition of timeouts and intervals as part of the Web API ({{domxref("setTimeout()")}} and {{domxref("setInterval()")}}), the JavaScript environment provided by Web browsers has gradually advanced to include powerful features that enable scheduling of tasks, multi-threaded application development, and so forth. To understand where `queueMicrotask()` comes into play here, it's helpful to understand how the JavaScript runtime operates when scheduling and running code. +Starting with the addition of timeouts and intervals as part of the Web API ({{domxref("setTimeout()")}} and {{domxref("setInterval()")}}), the JavaScript environment provided by Web browsers has gradually advanced to include powerful features that enable scheduling of tasks, multi-threaded application development, and so forth. To understand where {{domxref("Window.queueMicrotask()", "queueMicrotask()")}} comes into play here, it's helpful to understand how the JavaScript runtime operates when scheduling and running code. ## JavaScript execution contexts @@ -140,12 +140,12 @@ This is further alleviated by using [asynchronous JavaScript](/en-US/docs/Learn/ Microtasks are another solution to this problem, providing a finer degree of access by making it possible to schedule code to run before the next iteration of the event loop begins, instead of having to wait until the next one. -The microtask queue has been around for a while, but it's historically been used only internally in order to drive things like promises. The addition of `queueMicrotask()`, exposing it to web developers, creates a unified queue for microtasks which is used wherever it's necessary to have the ability to schedule code to run safely when there are no execution contexts left on the JavaScript execution context stack. Across multiple instances and across all browsers and JavaScript runtimes, a standardized microqueue mechanism means these microtasks will operate reliably in the same order, thus avoiding potentially difficult to find bugs. +The microtask queue has been around for a while, but it's historically been used only internally in order to drive things like promises. The addition of {{domxref("Window.queueMicrotask()", "queueMicrotask()")}}, exposing it to web developers, creates a unified queue for microtasks which is used wherever it's necessary to have the ability to schedule code to run safely when there are no execution contexts left on the JavaScript execution context stack. Across multiple instances and across all browsers and JavaScript runtimes, a standardized microqueue mechanism means these microtasks will operate reliably in the same order, thus avoiding potentially difficult to find bugs. ## See also - [Microtask guide](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) -- {{domxref("queueMicrotask()")}} +- {{domxref("Window.queueMicrotask()")}} - [The Event Loop](/en-US/docs/Web/JavaScript/Event_loop) - [Asynchronous JavaScript](/en-US/docs/Learn/JavaScript/Asynchronous) - [Introducing asynchronous JavaScript](/en-US/docs/Learn/JavaScript/Asynchronous/Introducing) diff --git a/files/en-us/web/api/html_dom_api/microtask_guide/index.md b/files/en-us/web/api/html_dom_api/microtask_guide/index.md index aa1d085ebbd45f7..089c330b2ecc8fc 100644 --- a/files/en-us/web/api/html_dom_api/microtask_guide/index.md +++ b/files/en-us/web/api/html_dom_api/microtask_guide/index.md @@ -10,7 +10,7 @@ A **microtask** is a short function which is executed after the function or prog This event loop may be either the browser's main event loop or the event loop driving a [web worker](/en-US/docs/Web/API/Web_Workers_API). This lets the given function run without the risk of interfering with another script's execution, yet also ensures that the microtask runs before the user agent has the opportunity to react to actions taken by the microtask. -JavaScript [promises](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) and the [Mutation Observer API](/en-US/docs/Web/API/MutationObserver) both use the microtask queue to run their callbacks, but there are other times when the ability to defer work until the current event loop pass is wrapping up is helpful. In order to allow microtasks to be used by third-party libraries, frameworks, and polyfills, the {{domxref("queueMicrotask()")}} method is exposed on the {{domxref("Window")}} and {{domxref("Worker")}} interfaces. +JavaScript [promises](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) and the [Mutation Observer API](/en-US/docs/Web/API/MutationObserver) both use the microtask queue to run their callbacks, but there are other times when the ability to defer work until the current event loop pass is wrapping up is helpful. In order to allow microtasks to be used by third-party libraries, frameworks, and polyfills, the {{domxref("Window.queueMicrotask()", "queueMicrotask()")}} method is exposed on the {{domxref("Window")}} and {{domxref("WorkerGlobalScope")}} interfaces. ## Tasks vs. microtasks @@ -36,7 +36,7 @@ There are two key differences. First, each time a task exits, the event loop checks to see if the task is returning control to other JavaScript code. If not, it runs all of the microtasks in the microtask queue. The microtask queue is, then, processed multiple times per iteration of the event loop, including after handling events and other callbacks. -Second, if a microtask adds more microtasks to the queue by calling {{domxref("queueMicrotask()")}}, those newly-added microtasks _execute before the next task is run_. That's because the event loop will keep calling microtasks until there are none left in the queue, even if more keep getting added. +Second, if a microtask adds more microtasks to the queue by calling {{domxref("Window.queueMicrotask()", "queueMicrotask()")}}, those newly-added microtasks _execute before the next task is run_. That's because the event loop will keep calling microtasks until there are none left in the queue, even if more keep getting added. > [!WARNING] > Since microtasks can themselves enqueue more microtasks, and the event loop continues processing microtasks until the queue is empty, there's a real risk of getting the event loop endlessly processing microtasks. Be cautious with how you go about recursively adding microtasks. @@ -47,7 +47,7 @@ Before getting farther into this, it's important to note again that most develop ### Enqueueing microtasks -As such, you should typically use microtasks only when there's no other solution, or when creating frameworks or libraries that need to use microtasks in order to create the functionality they're implementing. While there have been tricks available that made it possible to enqueue microtasks in the past (such as by creating a promise that resolves immediately), the addition of the {{domxref("queueMicrotask()")}} method adds a standard way to introduce a microtask safely and without tricks. +As such, you should typically use microtasks only when there's no other solution, or when creating frameworks or libraries that need to use microtasks in order to create the functionality they're implementing. While there have been tricks available that made it possible to enqueue microtasks in the past (such as by creating a promise that resolves immediately), the addition of the {{domxref("Window.queueMicrotask()", "queueMicrotask()")}} method adds a standard way to introduce a microtask safely and without tricks. By introducing `queueMicrotask()`, the quirks that arise when sneaking in using promises to create microtasks can be avoided. For instance, when using promises to create microtasks, exceptions thrown by the callback are reported as rejected promises rather than being reported as standard exceptions. Also, creating and destroying promises takes additional overhead both in terms of time and memory that a function which properly enqueues microtasks avoids. @@ -191,7 +191,7 @@ const logElem = document.getElementById("log"); const log = (s) => (logElem.innerText += `${s}\n`); ``` -In the following code, we see a call to {{domxref("queueMicrotask()")}} used to schedule a microtask to run. This call is bracketed by calls to `log()`, a custom function that outputs text to the screen. +In the following code, we see a call to {{domxref("Window.queueMicrotask()", "queueMicrotask()")}} used to schedule a microtask to run. This call is bracketed by calls to `log()`, a custom function that outputs text to the screen. ```js log("Before enqueueing the microtask"); @@ -220,7 +220,7 @@ const logElem = document.getElementById("log"); const log = (s) => (logElem.innerText += `${s}\n`); ``` -In the following code, we see a call to {{domxref("queueMicrotask()")}} used to schedule a microtask to run. This call is bracketed by calls to `log()`, a custom function that outputs text to the screen. +In the following code, we see a call to {{domxref("Window.queueMicrotask()", "queueMicrotask()")}} used to schedule a microtask to run. This call is bracketed by calls to `log()`, a custom function that outputs text to the screen. The code below schedules a timeout to occur in zero milliseconds, then enqueues a microtask. This is bracketed by calls to `log()` to output additional messages. @@ -287,7 +287,7 @@ log("Main program exiting"); ## See also - [In depth: Microtasks and the JavaScript runtime environment](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth) -- {{domxref("queueMicrotask()")}} +- {{domxref("Window.queueMicrotask()", "queueMicrotask()")}} - [Asynchronous JavaScript](/en-US/docs/Learn/JavaScript/Asynchronous) - [Introducing asynchronous JavaScript](/en-US/docs/Learn/JavaScript/Asynchronous/Introducing) - [Cooperative asynchronous JavaScript: Timeouts and intervals](/en-US/docs/Learn/JavaScript/Asynchronous) diff --git a/files/en-us/web/api/settimeout/index.md b/files/en-us/web/api/settimeout/index.md index 271ed39d6e2c44b..33b974e39119f1a 100644 --- a/files/en-us/web/api/settimeout/index.md +++ b/files/en-us/web/api/settimeout/index.md @@ -464,5 +464,6 @@ See also the [`clearTimeout()` example](/en-US/docs/Web/API/clearTimeout#example - [Polyfill of `setTimeout` which allows passing arguments to the callback in `core-js`](https://github.com/zloirock/core-js#settimeout-and-setinterval) - {{domxref("clearTimeout")}} - {{domxref("setInterval()")}} -- {{domxref("window.requestAnimationFrame")}} -- {{domxref("queueMicrotask()")}} +- {{domxref("Window.requestAnimationFrame")}} +- {{domxref("Window.queueMicrotask()")}} +- {{domxref("WorkerGlobalScope.queueMicrotask()")}} diff --git a/files/en-us/web/api/web_workers_api/functions_and_classes_available_to_workers/index.md b/files/en-us/web/api/web_workers_api/functions_and_classes_available_to_workers/index.md index 6f0bda99a158e94..88adc1acba0ab3d 100644 --- a/files/en-us/web/api/web_workers_api/functions_and_classes_available_to_workers/index.md +++ b/files/en-us/web/api/web_workers_api/functions_and_classes_available_to_workers/index.md @@ -24,8 +24,8 @@ Some of the functions (a subset) that are common to all workers and to the main - {{domxref("clearTimeout()")}} - {{domxref("createImageBitmap()")}} - {{domxref("WorkerGlobalScope.dump()", "dump()")}} {{non-standard_inline}} -- {{domxref("WorkerGlobalScope/fetch", "fetch()")}} -- {{domxref("queueMicrotask()")}} +- {{domxref("WorkerGlobalScope.fetch()", "fetch()")}} +- {{domxref("WorkerGlobalScope.queueMicrotask()", "queueMicrotask()")}} - {{domxref("reportError()")}} - {{domxref("setInterval()")}} - {{domxref("setTimeout()")}} diff --git a/files/en-us/web/api/web_workers_api/index.md b/files/en-us/web/api/web_workers_api/index.md index 5c9b4339d1e6c4c..6b2efe9d43bfaf0 100644 --- a/files/en-us/web/api/web_workers_api/index.md +++ b/files/en-us/web/api/web_workers_api/index.md @@ -48,8 +48,8 @@ Some of the functions (a subset) that are common to all workers and to the main - {{domxref("clearTimeout()")}} - {{domxref("createImageBitmap()")}} - {{domxref("WorkerGlobalScope.dump()", "dump()")}} {{non-standard_inline}} -- {{domxref("WorkerGlobalScope/fetch", "fetch()")}} -- {{domxref("queueMicrotask()")}} +- {{domxref("WorkerGlobalScope.fetch()", "fetch()")}} +- {{domxref("WorkerGlobalScope.queueMicrotask()", "queueMicrotask()")}} - {{domxref("reportError()")}} - {{domxref("setInterval()")}} - {{domxref("setTimeout()")}} diff --git a/files/en-us/web/api/window/index.md b/files/en-us/web/api/window/index.md index 3035129f6fbbf74..3e7ed8352b72744 100644 --- a/files/en-us/web/api/window/index.md +++ b/files/en-us/web/api/window/index.md @@ -219,7 +219,7 @@ _This interface inherits methods from the {{domxref("EventTarget")}} interface._ - : Returns the text entered by the user in a prompt dialog. - {{DOMxRef("Window.queryLocalFonts()")}} {{Experimental_Inline}} {{SecureContext_Inline}} - : Returns a {{jsxref("Promise")}} that fulfills with an array of {{domxref("FontData")}} objects representing the font faces available locally. -- {{domxref("queueMicrotask", "Window.queueMicrotask()")}} +- {{domxref("Window.queueMicrotask()")}} - : Queues a microtask to be executed at a safe time prior to control returning to the browser's event loop. - {{domxref("reportError", "Window.reportError()")}} - : Reports an error in a script, emulating an unhandled exception. diff --git a/files/en-us/web/api/window/queuemicrotask/index.md b/files/en-us/web/api/window/queuemicrotask/index.md index db9f93addddeddd..a72cda907ac3016 100644 --- a/files/en-us/web/api/window/queuemicrotask/index.md +++ b/files/en-us/web/api/window/queuemicrotask/index.md @@ -1,15 +1,14 @@ --- -title: queueMicrotask() global function +title: "Window: queueMicrotask() method" short-title: queueMicrotask() slug: Web/API/Window/queueMicrotask -page-type: web-api-global-function +page-type: web-api-instance-method browser-compat: api.queueMicrotask --- -{{APIRef("HTML DOM")}}{{AvailableInWorkers}} +{{APIRef("HTML DOM")}} -The **`queueMicrotask()`** method, -which is exposed on the {{domxref("Window")}} or {{domxref("Worker")}} interface, +The **`queueMicrotask()`** method of the {{domxref("Window")}} interface queues a microtask to be executed at a safe time prior to control returning to the browser's event loop. @@ -23,7 +22,7 @@ execution context, potentially depending on work you need to complete. You can l more about how to use microtasks and why you might choose to do so in our [microtask guide](/en-US/docs/Web/API/HTML_DOM_API/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()](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) for more details. +in a specific order. See [Using microtasks in JavaScript with `queueMicrotask()`](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) for more details. Microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks. @@ -31,12 +30,12 @@ final cleanup or other just-before-rendering tasks. ## Syntax ```js-nolint -queueMicrotask(() => {/* ... */}) +queueMicrotask(callback) ``` ### Parameters -- `function` +- `callback` - : A {{jsxref("function")}} to be executed when the browser engine determines it is safe to call your code. Enqueued microtasks are executed after all pending tasks have completed but before yielding control to the browser's event loop. @@ -84,6 +83,7 @@ MyElement.prototype.loadData = function (url) { ## See also +- {{domxref("WorkerGlobalScope.queueMicrotask()")}} - [Polyfill of `queueMicrotask()` in `core-js`](https://github.com/zloirock/core-js#queuemicrotask) - [Using microtasks in JavaScript with queueMicrotask()](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) - [Asynchronous JavaScript](/en-US/docs/Learn/JavaScript/Asynchronous) diff --git a/files/en-us/web/api/workerglobalscope/index.md b/files/en-us/web/api/workerglobalscope/index.md index a7f60c0a0fba49f..b68b64f61a84f73 100644 --- a/files/en-us/web/api/workerglobalscope/index.md +++ b/files/en-us/web/api/workerglobalscope/index.md @@ -66,7 +66,7 @@ _This interface inherits methods from the {{domxref("EventTarget")}} interface._ - : Starts the process of fetching a resource from the network. - {{domxref("WorkerGlobalScope.importScripts()")}} - : Imports one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: `importScripts('foo.js', 'bar.js');`. -- {{domxref("queueMicrotask()", "WorkerGlobalScope.queueMicrotask()")}} +- {{domxref("WorkerGlobalScope.queueMicrotask()")}} - : Queues a microtask to be executed at a safe time prior to control returning to the browser's event loop. - {{domxref("setInterval()", "WorkerGlobalScope.setInterval()")}} - : Schedules a function to execute every time a given number of milliseconds elapses. diff --git a/files/en-us/web/api/workerglobalscope/queuemicrotask/index.md b/files/en-us/web/api/workerglobalscope/queuemicrotask/index.md new file mode 100644 index 000000000000000..777906e77c43440 --- /dev/null +++ b/files/en-us/web/api/workerglobalscope/queuemicrotask/index.md @@ -0,0 +1,91 @@ +--- +title: "WorkerGlobalScope: queueMicrotask() method" +short-title: queueMicrotask() +slug: Web/API/WorkerGlobalScope/queueMicrotask +page-type: web-api-instance-method +browser-compat: api.queueMicrotask +--- + +{{APIRef("Web Workers API")}}{{AvailableInWorkers("worker")}} + +The **`queueMicrotask()`** method of the {{domxref("WorkerGlobalScope")}} interface +queues a microtask to be executed at a safe time prior to control returning to the +browser's event loop. + +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](/en-US/docs/Web/API/HTML_DOM_API/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()`](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) for more details. + +Microtasks are especially useful for libraries and frameworks that need to perform +final cleanup or other just-before-rendering tasks. + +## Syntax + +```js-nolint +queueMicrotask(callback) +``` + +### Parameters + +- `callback` + - : A {{jsxref("function")}} to be executed when the browser engine determines it is + safe to call your code. Enqueued microtasks are executed after all pending tasks have + completed but before yielding control to the browser's event loop. + +### Return value + +None ({{jsxref("undefined")}}). + +## Examples + +```js +queueMicrotask(() => { + // function contents here +}); +``` + +Taken from the [queueMicrotask spec](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#microtask-queuing): + +```js +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 + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- {{domxref("Window.queueMicrotask()")}} +- [Polyfill of `queueMicrotask()` in `core-js`](https://github.com/zloirock/core-js#queuemicrotask) +- [Using microtasks in JavaScript with queueMicrotask()](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) +- [Asynchronous JavaScript](/en-US/docs/Learn/JavaScript/Asynchronous) +- [queueMicrotask explainer](https://github.com/fergald/docs/blob/master/explainers/queueMicrotask.md) +- [Tasks, microtasks, queues and schedules](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/) by Jake Archibald diff --git a/files/en-us/web/javascript/guide/using_promises/index.md b/files/en-us/web/javascript/guide/using_promises/index.md index 673f62518af8ac7..112e4fc5804dde8 100644 --- a/files/en-us/web/javascript/guide/using_promises/index.md +++ b/files/en-us/web/javascript/guide/using_promises/index.md @@ -542,7 +542,7 @@ For more details, refer to [Tasks vs. microtasks](/en-US/docs/Web/API/HTML_DOM_A If you run into situations in which you have promises and tasks (such as events or callbacks) which are firing in unpredictable orders, it's possible you may benefit from using a microtask to check status or balance out your promises when promises are created conditionally. -If you think microtasks may help solve this problem, see the [microtask guide](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) to learn more about how to use [`queueMicrotask()`](/en-US/docs/Web/API/Window/queueMicrotask) to enqueue a function as a microtask. +If you think microtasks may help solve this problem, see the [microtask guide](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) to learn more about how to use {{domxref("Window.queueMicrotask()", "queueMicrotask()")}} to enqueue a function as a microtask. ## See also diff --git a/files/en-us/web/javascript/reference/operators/await/index.md b/files/en-us/web/javascript/reference/operators/await/index.md index 7ad0194e77ffeaf..ac1171edd3be712 100644 --- a/files/en-us/web/javascript/reference/operators/await/index.md +++ b/files/en-us/web/javascript/reference/operators/await/index.md @@ -237,7 +237,7 @@ function foo(name) { While the extra `then()` handler is not necessary, and the handler can be merged with the executor passed to the constructor, the `then()` handler's existence means the code will take one extra tick to complete. The same happens for `await`. Therefore, make sure to use `await` only when necessary (to unwrap promises into their values). -Other microtasks can execute before the async function resumes. This example uses [`queueMicrotask()`](/en-US/docs/Web/API/Window/queueMicrotask) to demonstrate how the microtask queue is processed when each `await` expression is encountered. +Other microtasks can execute before the async function resumes. This example uses {{domxref("Window.queueMicrotask()", "queueMicrotask()")}} to demonstrate how the microtask queue is processed when each `await` expression is encountered. ```js let i = 0;