Why does the click() method of html run synchronously?
P粉170438285
P粉170438285 2024-03-19 23:15:17
0
1
425

I found that MDN said that dispatchEvent() runs synchronously when introducing dispatchEvent(), but I did not find any official document like MDN or HTML Standard mentioning the html click() method Run synchronously or synthetic events run synchronously. Can someone share the relevant files with me? I'm really grateful!

Or maybe there are some explanations of execution steps in the document rather than direct conclusions? I noticed that both dispatchEvent() and click() will set the isTrusted property to false, but not sure if the eventListener call time depends on Here it is.

P粉170438285
P粉170438285

reply all(1)
P粉344355715

Each algorithm step does not say "parallel", "queue tasks", or anything in the specification linked to these will be executed synchronously. *

What’s in the specification algorithmdispatchThe target event is always executed synchronously. It comes from an EventTarget#dispatchEvent(), HTMLElement#click() or from an actual user initiated event.

Confusingly, for most cases, this scheduling event algorithm itself is wrapped in a queuing the task call , so actually the occurrence of the event will be asynchronous.

For example, when the image loads we have

Where "Queue Element Task" will call our Queue Task algorithm, and "Trigger Event" will call our > Scheduling Algorithm .

So, yes, in this case, the load event fires asynchronously after the image loading actually occurs.


Now, if we go back to EventTarget#dispatchEvent() (and HTMLElement#click( ), it boils down to a lot of events same build steps), we can see that it indeed calls the dispatch algorithm directly without queuing any new tasks.

Not only calls the algorithm synchronously, it even returns the result of the algorithm to the caller. Therefore the algorithm cannot be processed in parallel and the caller must call all handlers synchronously to get the result.

const makeEvent = (type) => new Event(type, { cancelable: true });
addEventListener("foo", (evt) => {
  console.log("foo fired");
});
console.log("return value", dispatchEvent(makeEvent("foo")));

addEventListener("bar", (evt) => {
  console.log("bar fired");
  evt.preventDefault(); // cancel the event
});
console.log("return value", dispatchEvent(makeEvent("bar")));

*Maybe there are other cases, but I don't know about them, and if they existed, they would surely be clear enough.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template