Make your code 3× faster with Asynchronous JavaScript.
First of all what is Asynchronous and synchronous, Let’s try to understand that.
What is Synchronous JavaScript ?
Let’s say you have few lines of code that fetches 3 image from a remote source. The normal way or the slow way of rendering the image is that we bring the first image then second and then third, and the whole process took approximately 3 seconds (1sec per image). In one line if i have to explain it i would say
One Hand for all task
now that we have an idea about synchronous, let’s see what is so special about asynchronous JavaScript
What is Asynchronous JavaScript ?
Now we are going to render all the three images together which brings down the time to load all the images, so now it just takes only one second for all the images to be rendered, In one line if i have to explain it i would say
Multiple Hands for Multiple Work
Now that we are knowing how the concept of asynchronous JavaScript, it’s time to see the code in action.
Time to Code
Can you tell the output of the following code ?
Obviously it’s
First
Second
Third
Fourth
Fifth
As we know that JavaScript run line of code in the order they are written, But what if we i just write my code this way
Now try to guess the output of this code, It will be
Second
Third
Fourth
Fifth
First
If you are like Woooooooooooh!!!!!!! make sure to follow me, But hey what just happened now. So when JavaScript executes the first line the setTimeout being an asynchronous function start’s but it does not stop the JavaScript for 3 seconds instead the code continues to run and after three second we get “First” printed. So there are two things working simultaneously. We used an inbuilt async(asynchronous) function now but can we make our own async function.
Async Function
We can create a function async using the async keyword, whenever we execute an async function in simple words we are adding one more hand for doing a work without stoping the main code.
Will soon write on complete Async JavaScript including Promises