Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
setTimeout macrotask in the UI event handler

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;

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!