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?