简体   繁体   中英

Microtask as macrotask in javascript code

I've found this note in whatwg spec:

It is possible for a microtask to be moved to a regular task queue, if, during its initial execution, it spins the event loop. This is the only case in which the source, document, and script evaluation environment settings object set of the microtask are consulted; they are ignored by the perform a microtask checkpoint algorithm.

What is an example of it, that expresses this quote? How is it possible to move a microtask from the microtask stack to the macrotask stack and perform it like a macrotask?

This was here for showModalDialog , which used to load a document in a modal, blocking the initial document until this modal is closed... For this to happen the UA had to "spin the event loop" until the modal's document is closed. This "spin the event loop" macro does convert the microtask to a "simple" task.

The showModalDialog() method has been removed from the specs but this remained since it can also be used in other modals or to allow "long tasks" to be short circuited by the UA, so that they can update the rendering and eg show a message to the user about the long script.
This is for instance advised in a note about pausing , called by all modals like alert() , prompt() , etc.:

Pausing is highly detrimental to the user experience, especially in scenarios where a single event loop is shared among multiple documents. User agents are encouraged to experiment with alternatives to pausing, such as spinning the event loop or even simply proceeding without any kind of suspended execution at all, insofar as it is possible to do so while preserving compatibility with existing content.

You also have that in some browsers with infinite loops, where they'll pause the script and show a message along the lines of " A script on this page is taking too long, do you want to wait or kill it with fire? ".

As an example, in Firefox, both cases will trigger a rendering update when the prompt is shown to the user, ie they do spin the event loop . So if the "pause" was triggered from inside of a microtask, they should move it to a macrotask when it's resumed.

However IIRC, they actually use a custom version of spin the event loop that only allow for the rendering phase (without callbacks) and nothing more. And the microtask isn't really converted to a task even there.
There are active discussions , where it is planned to "remove this concept" of reentering microtasks, since it's actually not really used by implementers. And even if it was, I'm not sure that'd be observable to us.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM