JavaScript

Demystifying the concepts of ‘Asynchronous JavaScript’

Javascript has been one of the vital constituents for application development nowadays in the world of information technology. Every application that is developed now is web-based, and when it comes to accessing the application through the web browser, you got to depend on javascript.

So, this blog is basically about breaking down the concepts of asynchronous requests in javascript which plays a vital role in how javascript functions. As we all know that javascript is single threaded, so definitely if we are to use synchronous calls for each and every action in the browser, then the browser must halt the rendering of the page in order to complete the execution of the javascript code. When the browser encounters synchronous javascript tag, it blocks the page from rendering until the code execution completes. Modern websites have moved from this method because it presents a direct risk to delaying page load time. The downside associated with this method is that the entire site is blocked from loading until the tag fully loads.

This can considerably slow response time associated with vendors, slow internet traffic etc. Now for the seamless experience of processing requests and rendering the page content in a web view, you have to depend upon asynchronous calls. This would not only separate javascript tags but also load them independently from each other. The asynchronous request minimises the impact of loading external javascript files on the page rendering process.

Functioning of Call Stack in Javascript

Javascript is a single threaded programming language, which means it has a single call stack and it can serve only one request at a time. Let us consider the following codebase

function multiply(a,b){
 return a*b;
}

function square(n){
 return multiply(n,n);
}

function printSquare(n){
 var lets_square = square(n);
 console.log(lets_square);
}

printSquare(4);

So, if we analyze the code I have three functions. The first function would multiply two numbers. The second function calls the multiply function and the third function calles the square function followed by a console.log.

Quick Fact: So, the call stack is basically the data structure which records where in the program we are. When we step into a function we push something onto the stack, when we return something from the function we pop up from the top of the stack. The objects that gets pushed in the call stack are referred to as stack frames. So each of the function within the call stack occupies a single stack frame.

So, if we follow the above codebase, diagramatically it can be represented as follows. When a function is called, it is pushed on to the stack. When the function returns a value, it is popped out from the stack.

So, the above diagram is a visual representation of how does javascript store elements within the call stack.

How does asynchronous javascript function work?

Now let us understand how is asynchronous javascript functioning. Let us look at a diagram first, which will clarify the interaction between the js runtime engine, Web APIs task queueand the event loop.

The js runtime engine consists of the

  1. The Heap which basically takes care of the memory allocation.
  2. The Call Stack which consists of all the javascript function.
  3. The Web APIs are threads provided by browsers that can only be requested for performing specific asynchronous operations.
  4. The Task Queue or the Callback Queue which consists of the event callbacks or tasks and
  5. The Event Loop which is responsible in transferring the tasks to be executed from the Task Queue to the Call Stack when the stack is empty.

Let us consider a small code snippet to understand how is the asynchronous request is processed in the back end.

console.log("Hi");

setTimeout(function cb(){
console.log('There');
}, 5000);

console.log("Christmas is just after one month");

The first function to be called in the stack is console.log("Hi");. We get ‘Hi’ in the console.

Next, the setTimeout(cb) is called to the stack. We pass the callback function and the timer to the setTimeout function. Now, remember the setTimeout is an API provided by the browser. Now, the browser is going to handle the timer specified in the code. The function call for setTimeout is complete so we can pop it out of the stack.

So, we have the timer in the Web API, which is going to complete after 5 seconds. Now the Web API cannot just start to modify the code otherwise, it would start appearing randomly. That is when the Task Queue or the Callback Queue kicks in.

Once the Web APIs are done, the callback gets pushed to the task queue, and finally we have the Event LoopEvent Loop is the simplest little piece in this whole equation and it has only one very simple job. It checks out the Call Stack and the Task Queue, if the Call Stack is empty it takes the first object in the Task Queue and pushes it onto the Call Stack which effectively runs it.

 Therefore, asynchronous javascript plays a very important role in the proper processing of the events and the callbacks. Without it, the rendering of contents within the pages become quite difficult and takes quite a toll on the performance and the response time for an application.

Published on Web Code Geeks with permission by Soumyajit Basu, partner at our WCG program. See the original article here: Demystifying the concepts of ‘Asynchronous JavaScript’

Opinions expressed by Web Code Geeks contributors are their own.

Soumyajit Basu

Soumyajit is a QA/DevOps engineer by profession and a technology enthusiast by passion. He loves communicating about technology and is an author at his own blog platform as well as in Dzone and Web Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button