Asynchronous Execution
Last updated
Last updated
Execution Process 1. Call Stack is filled with main(), console.log('Starting app') sequentially. 2. Waiting for console.log('Starting app') to finish, then setTimeout(2000) gets in. 3. The setTimeout(2000) is transferred to Node APIs and its clock starts ticking. 4. The setTimeout(0) gets in Call Stack. 5. The setTimeout(0) is transferred to Node APIs and its clock starts ticking. 6. The console.log('Finishing up') gets in Call Stack. 7. When setTimeout(0) in Node APIs is on due, it moves to Callback Queue. Only when Call Stack is empty, The Event Loop can pop item from Callback Queue to Call Stack. 8. After main() is done, the setTimeout(0) gets in Call Stack. 9. Item in setTimeout(0) reveals in Call Stack and gets execution. 10. The setTimeout(0) is done and leave from Call Stack. 11. When setTimeout(2000) in Node APIs is on due, it moves to Callback Queue. Since the Call Stack is empty, it can be popped to Call Stack. 12. Item in setTimeout(2000) reveals in Call Stack and gets execution.