Call back, Asynchronous JS, Web API, Event loop, Task Queue
Call back
One of the powerful concepts in JavaScript with which we can achieve asynchronous operation.
JavaScript is single threaded language, which means at a single time one line of execution will happen. As JavaScript is single threaded it is by default synchronous in nature. Primitive JavaScript is synchronous, by implementing concept of callback asynchronous operation can be achieved.
Let us say we want to create a function to fetch data from server, which is often long running operation. Similar task can be reading content of a file which is time taking, even if we want to implement concept of timer. In this case, JavaScript has to wait till task is completed, this will result entire page to be unresponsive. This was case earlier. All these problems can be solved by use of call back.
Let us design an activity to fetch data from server and perform some computation. This can be divided into following activity.
i) Fetching data from server - To be done by browser API.
ii) Performing some computation/display - To be done by JavaScript function.
We can implement call back function for performing computation and pass it to data fetching API, which will first fetch the data and then call the call back function to implement JavaScript code. This will not impact any other JavaScript code making operation asynchronous.
Web API -
Web API is library provided by browser, the functions and modules implemented (may be in C/C++) in this library is by default available for use and we can simply call the function to perform required operation. We can utilize these API's to perform intended operation and provide call back.
Here output would be
1
2
A
In this case, setTimeout function API is getting executed in parallel in browser call stack along with other JavaScript code. So, 1 and 2 are printed ahead of A as there is delay of 3 sec in printing A.
Comments
Post a Comment