=== update on Aug 18th, 2023
.click()
is synchronous
(I've made a mistake in my previous code snippet,
the callback in the Promise
constructor also runs synchronously)
if I add one line of Promise.resolve().then(() => console.log('then'))
, everything make sense!)
=== I've read lots of articles about event loop, but seems a few of them mentioned that is a DOM event handler a micro or a macro task?
and I was trying to figure it out by code, but something weird happened.
document.querySelector('#btn2').addEventListener('click', () => {
console.log('click btn2')
})
document.querySelector('#btn1').addEventListener('click', () => {
console.log('click btn1')
setTimeout(() => console.log('timer'));
new Promise(res => { console.log('promise');res(); });
document.querySelector('#btn2').click();
})
<button id="btn1">btn1</button>
<button id="btn2">btn2</button>
in this snippet, the console output is
click btn1
promise
click btn2
timer
so it seems to tell DOM event handler is a microtask
but when I adjust the line order in the code, I move the .click()
to the top
document.querySelector('#btn2').addEventListener('click', () => {
console.log('click btn2')
})
document.querySelector('#btn1').addEventListener('click', () => {
document.querySelector('#btn2').click();
console.log('click btn1')
setTimeout(() => console.log('timer'));
new Promise(res => { console.log('promise');res(); });
})
<button id="btn1">btn1</button>
<button id="btn2">btn2</button>
click btn2
click btn1
promise
timer
the click
event runs before the sync code?
can someone explain this to me, thanks