Open In App

Synchronous and Asynchronous in JavaScript

Last Updated : 14 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Synchronous JavaScript

As the name suggests synchronous means to be in a sequence, i.e. every statement of the code gets executed one by one. So, basically a statement has to wait for the earlier statement to get executed.

Example: In this example, we have shown the synchronous nature of JavaScript.

javascript




document.write("Hi"); // First
document.write("<br>");
 
document.write("Mayukh");// Second
document.write("<br>");
 
document.write("How are you"); // Third


Output:

In the above code snippet, the first line of the code Hi will be logged first then the second line Mayukh will be logged and then after its completion, the third line will be logged How are you. So as we can see the codes work in a sequence. Every line of code waits for its previous one to get executed first and then it gets executed.

Asynchronous JavaScript

Asynchronous code allows the program to be executed immediately whereas the synchronous code will block further execution of the remaining code until it finishes the current one. This may not look like a big problem but when you see it in a bigger picture you realize that it may lead to delaying the User Interface.

Example: In this example, we have shown the Asynchronous nature of JavaScript.

javascript




document.write("Hi");
document.write("<br>");
 
setTimeout(() => {
    document.write("Let us see what happens");
}, 2000);
 
document.write("<br>");
document.write("End");
document.write("<br>");


Output:

So, what the code does is first it logs in Hi then rather than executing the setTimeout function it logs in End and then it runs the setTimeout function.

At first, as usual, the Hi statement got logged in. As we use browsers to run JavaScript, there are the web APIs that handle these things for users. So, what JavaScript does is, it passes the setTimeout function in such web API and then we keep on running our code as usual. So it does not block the rest of the code from executing and after all the code its execution, it gets pushed to the call stack and then finally gets executed. This is what happens in asynchronous JavaScript.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads