Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execution Order in Event Loop

Tags:

javascript

why setTimeout(callback), Promise.resolve().then(callback) and requestAnimationFrame(callback) have different priority to execute? Following is a code sample:

setTimeout(()=>console.log(1));
Promise.resolve(2).then(console.log);
requestAnimationFrame(()=>console.log(3));
console.log(4);
window.onclick = ()=>console.log(5);
window.dispatchEvent(new Event('click'));
like image 387
trigold Avatar asked Aug 31 '26 15:08

trigold


1 Answers

synchronization

  console.log(4);
  window.onclick = ()=>console.log(5);
  window.dispatchEvent(new Event('click'));

Micro tasks

 Promise.resolve(2).then(console.log);
  requestAnimationFrame(()=>console.log(3));

Macro task

  setTimeout(()=>console.log(1));

like image 146
vueAng Avatar answered Sep 02 '26 04:09

vueAng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!