Get knowledge of web designing, SEO and android architecture

Calling javascript function “asynchronously”

Javascript is not a multi-threaded programming language, because it is not multi-threaded we can’t call a function asynchronously, but there is workaround (or hack) to call functions asynchronously in javascript.

The advantages of calling functions asynchronously is that the script runs without waiting for the return value from the function which is called.

To make a function asynchronous we need to encapsulate the function in a method that by-pass the function without waiting for its return value.

To do so, we will use setTimeout() function in javascript.

Let’s learn how to call a function asynchronously in javascript:

For example we want to call fetch() function asynchronously, we need to call this function using setTimeout() method.

1

2

3

4

5

6

7

8

9

10

11

functionasync() {

setTimeout(function(){

fetch();

},0);

}

async(); // It will call the fetch() function asynchronously

Now when we want to call the fetch() function asynchronously we just need to call the async() function.

Still javascript is not asynchronous

Javascript is a single-threaded programming language, and it can not call functions asynchronously (at-least for now). The code above will emulate asynchronous call method, but the processing will be done in the form of single block process. So we can say that setTimeout() create an illusion of asynchronous call.