This content originally appeared on DEV Community and was authored by Badr Eddine El-Harchali
If you want to build projects efficiently, then this concept is for you.
The theory of async JavaScript helps you break down big complex projects into smaller tasks.
Then you can use any of these three techniques – callbacks, promises or Async/await – to run those small tasks in a way that you get the best results.
Let's dive in!?️
Synchronous vs Asynchronous JavaScript
What is a Synchronous System?
In a synchronous system, tasks are completed one after another.
Think of this as if you have just one hand to accomplish 10 tasks. So, you have to complete one task at a time.
Take a look at the GIF ? – one thing is happening at a time here:
You'll see that until the first image is loaded completely, the second image doesn't start loading.
Well, JavaScript is by default Synchronous [single threaded]. Think about it like this – one thread means one hand with which to do stuff.
What is an Asynchronous System?
In this system, tasks are completed independently.
Here, imagine that for 10 tasks, you have 10 hands. So, each hand can do each task independently and at the same time.
Take a look at the GIF ? – you can see that each image loads at the same time.
Again, all the images are loading at their own pace. None of them is waiting for any of the others.
To Summarize Synchronous vs Asynchronous JS:
When three images are on a marathon, in a:
**Synchronous **system, three images are in the same lane. One can't overtake the other. The race is finished one by one. If image number 2 stops, the following image stops.
**Asynchronous **system, the three images are in different lanes. They'll finish the race on their own pace. Nobody stops for anybody:
Synchronous and Asynchronous Code Examples:
Let's look at some examples and clear up any doubts.
Synchronous Code Example
To test a synchronous system, write this code in JavaScript:
console.log(" I ");
console.log(" eat ");
console.log(" Ice Cream ");
Here's the result in the console: ?
Asynchronous code example
Let's say it takes two seconds to eat some ice cream. Now, let's test out an asynchronous system. Write the below code in JavaScript.
Note: Don't worry, we'll discuss the setTimeout()
function later.
console.log("I");
// This will be shown after 2 seconds
setTimeout(()=>{
console.log("eat");
},2000)
console.log("Ice Cream")
And here's the result in the console: ?
Here's your medal for reading until the end. ❤️
Suggestions and criticisms are highly appreciated ❤️
This content originally appeared on DEV Community and was authored by Badr Eddine El-Harchali
Badr Eddine El-Harchali | Sciencx (2021-06-18T11:33:18+00:00) What is Asynchronous JavaScript?. Retrieved from https://www.scien.cx/2021/06/18/what-is-asynchronous-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.