{"id":157,"date":"2020-06-06T13:20:50","date_gmt":"2020-06-06T13:20:50","guid":{"rendered":"https:\/\/danwritescode.com\/?p=157"},"modified":"2020-06-08T15:07:40","modified_gmt":"2020-06-08T15:07:40","slug":"what-happens-in-the-event-loop-when-we-run-asynchronous-javascript-code","status":"publish","type":"post","link":"https:\/\/danwritescode.com\/what-happens-in-the-event-loop-when-we-run-asynchronous-javascript-code\/","title":{"rendered":"What Happens In The Event Loop When We Run Asynchronous Javascript Code?"},"content":{"rendered":"\n
In the previous post we saw a simple example of asynchronous javascript code. Let’s dive deeper into the subject and see what happens in the event loop in the case of asynchronous code.<\/p>\n\n\n\n
Recap on the main difference between synchronous and asynchronous code: When running asynchronous code:<\/strong><\/p>\n\n\n\n Basically we can use callback functions to push actions into the future so that the code becomes non-blocking.<\/p>\n\n\n\n But how does this work? Let me try to explain what happens in the event loop, and try some “art” while I’m at it.<\/p>\n\n\n\n What happens behind the scenes of javascript?<\/p>\n\n\n\n The event loop is part of what happens behind the scenes of javascript when functions and events (like DOM events) happen. <\/p>\n\n\n\n Let’s define the structure of the Javascript Runtime. The Javascript Runtime is where the code is executed when we run it. Just a quick reminder, below there there is my asynchronous javascript code with which I will explain how the event loop works:<\/p>\n\n\n\n Here’s a representation of the Javascript Runtime with the execution stack, web APIs, the callback queue and the even loop. Let’s go through this code instruction by instruction and see how it looks like.<\/p>\n\n\n\n First up when the program initializes, the execution stack will contain only the global execution context.<\/p>\n\n\n\n
When writing synchronous code: <\/strong><\/p>\n\n\n\n
The Javascript Runtime is made out of:<\/p>\n\n\n\n
It is important to understand how each piece works and how they work together so we can execute asynchronous javascript.<\/p>\n\n\n\nconst two= () => {\n console.log(2);\n}\n\nconst go = () => {\n console.log(1);\n two();\n console.log(3);\n}\n\ngo();<\/code><\/pre>\n\n\n\n