Sunday, August 8, 2021

What is an event loop in JavaScript?

Must read

The event loop in javascript is the real magic behind the asynchronous behavior. All the operations are working on a single thread in javascript but javascript uses some data structure to accomplish the illusion of multi-threading.

The data structures used are “Call Stack” and “Event Queue

Understanding “Call Stack” in javascript

The call stack is used for keeping the track of all the operations which are to execute, like what function is being executed and what function is being called by this function.

Let’s take an example:


function third() {  
  console.log("third function called, end of line")
}
function second() { 
  console.log("second function called")
  third();
}
function first() { 
  console.log("first function called");
  second();
}
first();


Visualizing Call Stack

Let’s look into the visualization of call stack of event loop in JavaScript, for our visualizations, we will be using “http://latentflip.com/loupe/

The Output will be:

"first function called"
"second function called"
"third function called, end of line"

Code explanation:

  • first() function is called, then console.log(“first function called”) and executed. The first() function remains in the stack.
  • second() function is called, then console.log(“second function called”) and executed. The second() function remains in the stack.
  • third() function is called, then console.log(“third function called, end of line”) and executed. The third() function remains in the stack.
  • After the code is executed for the third() function the stack starts to pop all the functions which are in the stack starting from the top, third() function, then second() function, then first() function. and then the stack is empty.

Understanding “Event Queue” in javascript

Event Queue is used for processing of new functions, which is done using queue data structure so that a correct sequence is followed to execute these functions.

When an async function is called in javascript, it is first sent to the Browser API. This Browser API starts its own single treaded options once the function is received.

One of the Examples of the async function is setTimeout().

Let’s take an example and understand the flow:

function second() {
}

function first() {
     second();
}

setTimeout ( 
	function() {
     console.log ( "set time out called" )
	},8000);
   
first();

The Output will be:

"first function called"
"second function called, end of line"
"set time out called" // after 8 seconds

Visualizing Call Stack, Event Queue, Web Api’s

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article