If there arises a requirement where the application which we create should be flexible, fast and efficient, Asynchronous Programming is your best bet!
JavaScript is a synchronous and single threaded programming language. But if we need to perform multiple tasks simultaneously instead of waiting, asynchronous JavaScript comes into picture.
Asynchronous JavaScript solves a lot of problems which are caused due to the single threaded nature of JavaScript as it can multitask.
To use Asynchronous Programming in JavaScript, one of the fundamental functions is setTimeOut(). setTimeOut takes in two arguments:
- The callback function
- Time in milliseconds
the callback function describes the necessary task which the setTimeOut should perform after the described time limit given.
Syntax:
setTimeOut(() => {
console.log(“Hello World”);
}, 4000);
So after the program is executed, Hello World appears on the console after 4000 milliseconds i.e. 4 seconds.
This can be associated with another scenario:
Example:
setTimeOut(() => {
console.log(“Inside setTimeOut”);
}, 4000);
console.log(“Outside setTimeOut”);
In the above scenario, while using other programming languages it can be assumable that Inside setTimeOut will appear on the console first and Outside setTimeOut will appear next.
But that is entirely opposite in case of JavaScript!
after identifying that the setTimeOut function will be called after 4000 milliseconds, the JS engine will try to execute the other part of the code which is to log Outside setTimeOut on the console.
This will lead to execute the console.log(“Outside setTimeOut”) statement first and the console.log(“Outside setTimeOut”) will get executed after 4000 milliseconds.
This ensures to eliminate idle time as the other part of code gets executed instead of waiting for the setTimeOut function
to complete execution.
Having knowledge on Asynchronous JavaScript is vital in creating efficient and responsive Web Applications.
It handles Input/Output operations smoothly, it improves User Experience and it enables concurrency in the application.