Order
According to the documentation, if the same event is registered multiple times, it will be executed in the order of registration.
Microtasks will be processed after the current main thread has finished and before the next task is triggered.
However, between events, whether microtasks are executed before or after the event is not clear.
Test Code
document.addEventListener('mousemove', function (event) {
console.log('mousemove1')
setTimeout(() => {
console.log('setTimeout')
})
Promise.resolve().then(function () {
console.log('Promise')
})
queueMicrotask(() => {
console.log('queueMicrotask')
})
})
document.addEventListener('mousemove', function (event) {
console.log('mousemove2')
})
document.addEventListener('mousemove', function (event) {
console.log('mousemove3')
})
console.log('sync')
Test Results
sync
mousemove1
Promise
queueMicrotask
mousemove2
mousemove3
setTimeout
mousemove1
Promise
queueMicrotask
...
Events are executed in order, and microtasks are executed immediately after an event has been processed.
Microtasks maintain their order of execution.
setTimeout is executed after both events and microtasks have been executed.
Multiple Executions of setTimeout
When events are triggered too quickly, setTimeout will be postponed to the next round.
sync
mousemove1
Promise
queueMicrotask
mousemove2
mousemove3
mousemove1
Promise
queueMicrotask
mousemove2
mousemove3
setTimeout
setTimeout
It seems that neither setTimeout nor microtasks are suitable for setting up logic to be executed after an event.