0

window.onload = () => {
    var button = window.btn1 = document.querySelector("#btn1");
    button.addEventListener(
        "click",
        () => {
            console.log("task 1");
            Promise.resolve("promise 1").then(console.log);
        },
        false
    );
    button.addEventListener(
        "click",
        () => {
            console.log("task 2");
            Promise.resolve("promise 2").then(console.log);
        },
        false
    );
}
<button id="btn1">handle click event</button>
<button onclick="btn1.click()">run .click()</button>

When I clicked the button, I thought the output would be:

task1, task2, promise1, promise2

but the result is:

task1, promise1, task2, promise2

One event handler will be treated as one macrotask?

One the other way, If I trigger the click event by code: button.click(), the output is:

task1, task2, promise1, promise2

I know triggering the event by code will only be handled by the browser's main thread. The real click is different. But, Any one can explain it deeply?

Nickolay
  • 31,095
  • 13
  • 107
  • 185
coypan
  • 133
  • 7
  • "*One event handler will be treated as one macrotask?*" - yes, apparently. – Bergi Aug 15 '19 at 12:54
  • If I trigger the event by code, it seems that all the event hanlders are treated as one macrotask。Is there any document to explain it ? – coypan Aug 15 '19 at 12:58
  • You may want to look at [this answer to "Javascript API to explicitly add micro tasks or macro tasks"](https://stackoverflow.com/a/41076879/215552) which has links to the various standards that define task/job queues. – Heretic Monkey Aug 15 '19 at 13:03
  • [Jake Archibald's talk at JSConf.Asia 2018](https://www.youtube.com/watch?v=cCOL7MC4Pl0) has an extremely good explanation of microtasks and their place in the event loop. Highly recommend watching it. – David784 Aug 15 '19 at 13:20
  • 1
    Duplicate of [Why is there a difference in the task/microtask execution order when a button is programmatically clicked vs DOM clicked?](https://stackoverflow.com/questions/55709512/why-is-there-a-difference-in-the-task-microtask-execution-order-when-a-button-is) – Nickolay Aug 16 '19 at 17:09

0 Answers0