You are currently viewing Asynchronous JavaScript

Asynchronous JavaScript

Asynchronous JavaScript

Asynchronous JavaScript

In this article we will read about asynchronous concept of JavaScript. Before reading it you should have knowledge about JavaScript fundamentals.

There are two types of programing language – Synchronous and Asynchronous.

Till now we have read about Synchronous JavaScript. But in this tutorial, you will read about Asynchronous JavaScript.

Now we will see about Synchronous JavaScript.

Synchronous JavaScript

Synchronous JavaScript means every line will be executed after the execution of the first line before it. Synchronous JavaScript is single-threaded means only one operation can be executed at a time. After the execution of one operation, the next will get executed.

Every function will execute in sequential order. Each waiting for the first function/line of code to execute before it executes the next function or line of code.

For example:

let’s take a simple example ,

let a = 10;
let b = 20;
console.log(a);
let sum = a+b;
console.log(sum);

In this example , initially first line of console.log() will be execute. After execution of first line then sum will be printed.

Asynchronous JavaScript

For example,

console.log("Welcome !");

setTimeout(function() {
  console.log("JavaScript!");
}, 5000);

console.log("Hello World!");
Output

Here, Initially Welcome! will be printed to the console , it go to next function and it see setTimeout function, but instead of waiting for 5s for prints the JavaScript! it goes to the next function and print Hello World! to the console. and then after 5s JavaScript! get printed to the console. Here two functions are running in parallel. This is known as Asynchronous JavaScript.

This example shows the Asynchronous behavior of JavaScript.

Also we can use setInterval function which will print JavaScript! to the console after every 5s.

console.log("Welcome !");

setInterval(function() {
  console.log("JavaScript!");
}, 5000);

console.log("Hello World!");
JavaScript! will get printed after every 5s

So, setTimeout and setInterval are good example of Asynchronous.

In this tutorial you have read about Synchronous and Asynchronous JavaScript.

Article written By: : Ankita Kataria.

Check Modules and Currying in JavaScript.

Thank you !!

This Post Has 3 Comments

Leave a Reply