1

I realized that the requestAnimationFrame callback also pushed to a queue like the promise, does anyone explain the code, why console.log(2) is running before console.log(1)

requestAnimationFrame(() => {
  console.log(1)
})


const end = Date.now() + 2000;
while (Date.now() < end) {
}

console.log(2)
ChenLee
  • 1,371
  • 3
  • 15
  • 33
  • There is a [YouTube video by Jake Archibald (“In The Loop”)](//youtu.be/cCOL7MC4Pl0) which is an excellent introduction to the event loop. But in your code, it’s quite trivial. You have one asynchronously executed function (the rAF callback); the rest is synchronous code. The async code’s _only chance_ to run is _after_ the synchronous code that initiated it finishes. It does not matter how long it takes the synchronous code to finish. – Sebastian Simon Dec 24 '21 at 06:25
  • Your `while` loop is called “busy waiting”. Look up the relationship between that and the event loop. Related: [how event loop exactly executes code in 2 seconds if the code is larger and call stack is not empty?](/q/66746092/4642212), [How does Javascript event loop handle the execution of a nonblocking function call after event gets dequeued?](/q/54376959/4642212). – Sebastian Simon Dec 24 '21 at 06:32

0 Answers0