0
setTimeout(()=>{console.log("Testing")}, 0);

console.log("Next");

Hello guys, i wanted to ask how does the javascript engine interpret asynchronous code? In the above code, its the setTimeout function setup and then console.log is called or does the javascript engine first execute synchronous code first followed by the setting up of other asynchronous code?

  • 1
    Possible duplicate of [What is setTimeout doing when set to 0 milliseconds?](https://stackoverflow.com/questions/33955650/what-is-settimeout-doing-when-set-to-0-milliseconds) – Sebastian Simon Nov 12 '19 at 18:26
  • setTimeout is always asynchronous. Asynchronous events are always queued. There is only one execution context per environment. Execution contexts cannot be preempted in the same environment. – user2864740 Nov 12 '19 at 18:33

1 Answers1

0

response of your code will be

Next
Testing

Quick and dirty explanation: there are 2 objects in javascript environment - execution stack and message queue. Javascript moves current function to the execution stack and execute it line by line. If there is asynchronous call like setTimeout (even with delay 0 like in your case) it is not executed on the place. Instead it moves to the message queue. Execution stack is processed until the moment it is completely empty. In that moment top object from message queue is moved to the execution stack.

IgorK
  • 148
  • 8