button.addEventListener(
'click',
(event) => {
console.log('listener 1')
queueMicrotask(() => {
console.log('microtask')
})
}
)
button.addEventListener(
'click',
(event) => {
console.log('listener 2')
}
)
The order should be
listener 1
microtask
listener 2
For first click event task:
- after finish
console.log('listener 1')
, callstack is empty - then because of callstack is empty, microtask will be executed
- Then second click event will be added to callstack
But things got changed for dispatchEvent
button.addEventListener(
'click',
(event) => {
console.log('listener 1')
queueMicrotask(() => {
console.log('microtask')
})
}
)
button.addEventListener(
'click',
(event) => {
console.log('listener 2')
}
)
button.dispatchEvent(new MouseEvent('click'))
Order:
listener 1
listener 2
microtask
- dispatchEvent will stay, so the callstack is not empty
- therefore first run listener 1
- then listener 2
- then microtask