i wrote following simple react component
in the onBlur event handler, i create a new macrotask by setTimeout
function App() {
const onBlur=()=>{
console.log('onBlur')
setTimeout(() => {
console.log('setTimeout')
}, 0);
}
const onClick=()=>{
console.log('onClick')
}
return (
<div className="App">
<div id="first" onClick={onClick}>aaa</div>
<div id="second" contentEditable onBlur={onBlur} suppressContentEditableWarning>qq</div>
</div>
);
}
and then
1、i move the mouse pointer into second div
2、then i click the first div
it print out with following sequence in the console
onBlur
setTimeout
onClick
my question is why setTimeout displays before onClick;
apprecaite your answers; please help me; thank you very much;
Because the blur event is fired from the mousedown event, while the click event is made of both mousedown and mouseup.
const d1 = document.querySelector("div");
const d2 = document.querySelector("div[contenteditable]");
d1.addEventListener("mousedown", ({type}) => {
console.log(type);
setTimeout(() => console.log("timeout from %s", type), 0);
});
d1.addEventListener("click", ({type}) => console.log(type));
d1.addEventListener("mouseup", ({type}) => console.log(type));
d2.addEventListener("blur", ({type}) => {
console.log(type);
setTimeout(() => console.log("timeout from %s", type), 0);
});
d2.focus();
/* expected output:
mousedown
blur
timeout from mousedown
timeout from blur
mouseup
click
*/
<div>CLICK ME</div>
<div contenteditable>focused element</div>
So by the time you release your mouse pointer, the blur event has already been fired and the 0 timeout also had time to get executed, unless if you can do so in less than one ms in Chrome, where they have a 1ms minimum timeout.