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.
Recap on the main difference between synchronous and asynchronous code:
When writing synchronous code:
- We run one instruction after another
When running asynchronous code:
- We allow asynchronous functions to run in the background (such as setTimeout() functions or functions which take a longer time to process)
- We pass callbacks to these functions which run once the function finished whatever work it was doing
- We continue with the execution of the code immediately. This is means that the code is non-blocking.
Basically we can use callback functions to push actions into the future so that the code becomes non-blocking.
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.
What happens behind the scenes of javascript?
The event loop is part of what happens behind the scenes of javascript when functions and events (like DOM events) happen.
Let’s define the structure of the Javascript Runtime. The Javascript Runtime is where the code is executed when we run it.
The Javascript Runtime is made out of:
- The Execution Stack
- Web APIs
- The Message Queue
- The Event Loop
It is important to understand how each piece works and how they work together so we can execute asynchronous javascript.
Just a quick reminder, below there there is my asynchronous javascript code with which I will explain how the event loop works:
const two= () => {
console.log(2);
}
const go = () => {
console.log(1);
two();
console.log(3);
}
go();
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.
First up when the program initializes, the execution stack will contain only the global execution context.
This was a very basic example of how the event loop works with asynchronous code. If you want to know how more complex code would act, you can draw your own diagrams, but it will follow the same procedure, just at a different scale.