Search code examples
javascriptsettimeout

Call Stack Priority in JavaScript


If 'A' goes into callback queue and 'B' and 'C' both still have to be executed, will A run after B (assuming that its timeout is complete), or will C run first?

I assume it will be A?


Solution

  • Here is a proof of concept.

    setTimeout(()=> console.log('C'), 500);
    setTimeout(()=> console.log('B'), 500);
    
    
    for (let i=0; i <= 99999; i++)
      for (let j=0; j <= 99999; j++)
        if (i === 9999 && j === 9999)    //< Note that the loop still continues after this
          setTimeout(()=> console.log('A'), 0); //Note the zero

    Here is a guide:

    https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5