All about asynchronous javascript
How to perform multiple tasks at the same time in Javascript❓❓
Namastey🙏 to all the readers
Ever wondered🤔 how Javascript is able to do time-consuming operations or do multiple operations at the same time, then you are at the right place.
Prerequisites
Before reading this article, I would highly recommend reading the following article https://bit.ly/2Zbtmnn so that you are in a better position to understand this article.
What we will cover in this article
How does synchronous javascript works
How does asynchronous javascript works
How does synchronous javascript works
Before understanding how asynchronous javascript works, let's first understand how synchronous javascript code works.
Synchronous Javascript as the name implies, means in a sequence, or an order. Here, every function or program is done in a sequence, each waiting for the first function to execute before it executes the next, synchronous code goes from top to bottom.
Synchronous operation visual representation👇
In the above animation🤘, only one task is executed at one time. Let's understand with the help of synchronous code example
console.log("welcome to asynchronous javacript");
function add(a, b) {
return a + b;
}
add(2, 3);
But Wait
Before understanding how the above code executes inside the javascript engine, we have to understand the concept of execution context and Callstack
Execution Context
Execution Context is a container in which Javascript code is evaluated and executed. When we run a Javascript code, its runs inside an execution context.
There are two types of execution context
Global execution context -> Code present inside the global scope is run inside the global execution context.
Function execution context -> Code present inside the function scope is run inside the function execution context.
Callstack
Callstack as the name implies is a stack that is used to store all the execution context created during the code execution. Javascript has a single Callstack because it's a single-threaded programming language i.e only one operation can be executed at a time.
Now we have a better understanding of execution context and Callstack So let's get back to the above code snippet and try to understand how the code executes inside the Javascript engine.
Till now we have learned how synchronous javascript works. Now let's dive deep into the world of asynchronous javascript🚀🚀
How does asynchronous Javascript works
In asynchronous Javascript, we want to perform such tasks which are not executed immediately but required a certain intervals of time to execute like timing operations, network requests, event listeners, etc.
Asynchronous operation visual representation
In the above animation🤘, multiple tasks are executed at the same time But how we can perform such types of tasks in Javascript as Javascript is a single-threaded language.
To understand it please welcome👏👏 our new member the Browser. So Browser provides us superpowers due to which we can perform asynchronous operations.
What are these Browser superpowers
Browser superpowers are features given by the browser to the Javascript engine by which we can access these features in our Javascript code. Due to these features, we can track the location, access Bluetooth, etc... in our Javascript code.
But How Javascript engine access the features provided by browser❓
To understand it please welcome👏👏 our new member the WebAPI.
WebAPI
WebAPI's is an abstract environment that provides access to the browser superpowers💪. These are provided by the browser to the Javascript engine through the global object(in the browser it is known as window object).After a callback is registered it is stored inside the WebAPI environment. It is present inside Javascript runtime environment which in our case is browser.
Let's understand how asynchronous Javascript work with the help of an example
console.log("before settimeout function is called");
setTimeout(()=>{
console.log("inside set timeout function");
},0)
console.log("after settimeout function is called");
Before understanding how the above code executes inside the javascript engine, we have to understand the concept of Callback queue and Event loop.
Callback queue
Callback queue as the name suggests is a queue that stores all the callbacks except callbacks from promises and mutation observers. It is also present inside Javascript runtime environment which in our case is browser.
Event loop
The event loop is also part of Javascript runtime environment which in our case is browser. It is used to check whether the Callstack is empty or not and if Callstack is empty it then checks if there is any callback present inside Callback queue and if it founds there is a callback then it pushes that callback into Callstack.
Understanding event loop by below statement
Callstack empty && callback present inside callback queue => push callback to Callstack
Now we have a better understanding of callback queue and event loop. So let's get back to the above code snippet and try to understand how the code executes inside the Javascript engine with the help of images.
See the image below👇 to understand what happens when the first statement of code is executed
After executing the first statement control moves to execute the next statement which is called the setTimeout function which performs the asynchronous tasks. The callback which is passed as the first argument to setTimeout is registered inside the WebAPI environment and simultaneously timer is also set to the time given by the second argument
As javascript is a single-threaded language it will not wait for the callback of setTimeout function to be fully executed and moves to the next statement and executes it.
After executing the last statement there is no further statement to execute in the global scope so the global execution context get popped from the stack
Now one question arises in my mind that how callback will be executed by the Javascript engine.
Yes, you are right we need to push callback into Callstack so that it can be executed.
Okay, so how we will push callback into Callstack
Take a break and meditate on it🤔
Yes, you are right, remember our two old friends event loop and Callstack. Both of them will help us to push callback into callstack. Check the image below👇
After the callback has executed code inside it👇
So this is how asynchronous Javascript works.
Conclusion
Congratulations on reading until the end! In this article, you've learned
how synchronous code in javascript works behind the scenes
how asynchronous code in javascript works behind the scenes
I hope you enjoyed😃 reading the article. Thanks for reading!!
Please provide feedback on the content of the article.
You can connect with me on social media👇