Event Loop In Javascript

Event Loop In Javascript

Call Stack, Web APIs, Event/Callback Queue

JavaScript

As most developers might come across the statement that "JavaScript is a single-threaded programming language, that can do only one thing at a single point in time."

It means, If a function is taking a huge amount of time in the execution, then you will face the issue of blocking the user interface, and you cannot interact with the web browser until it finishes with its execution.

Below is an example just to show, what if our API takes such a huge amount of time for fetching data from the server-side. 😢

function fetch(num) {
    // time consuming task
    for(let i= 0; i<99999999999; i++){
           console.log(num*i);
     }     
}

console.log('Start');
fetch(4);
console.log('Done!');

You may relate to such situations hang.gif

Do you ever wonder? How does JavaScript handle such tasks and perform parallel operations?

Event Loop is the master behind all of those asynchronous behaviours!

What is an event loop? It's a program which keeps on checking, if the call stack is empty, if so, then it looks into the event queue and pulls the pending operations one by one into the call stack until the queue gets empty. ......#%$#%&$#@@$%%$#@..... 😐

confused-c2e1e9d14491a9486d996da945debcc9d6ce7170-s800-c85.webp For the first, it might sound confusing, what the heck is Call Stack, Event/Callback Queue, *How does it checks the queue. 😕

Understand, How all they work together.

1. What is a Heap/Memory Heap - A large space to store objects and functions

2. What is Call Stack - Call stack is like a bucket, where an item that goes last will come out first.**

In a technical term, it is a LIFO (last in first out) data structure. Where all your javascript code is stored and getting executed line by line. It is popped/taken out from the stack after finishing with the execution.

3. Web API - An outside person assisting in solving some of your problems.

As we all know, that Javascript cannot perform a parallel operation, because it is a single-threaded language. And when the JS engine has to deal with asynchronous code, it takes the help of Web API, which handles the blocking behaviour of JavaScript code. Some of the web APIs are

  • DOM
  • Ajax (Network requests)
  • SetTimeout()

4. Event or Callback Queue - It's like a line of people waiting to buy some groceries: the person comes first, goes out first

It stores the callbacks resolved by the Web APIs and waits here to get called, to go back to the Call Stack.

It also works in a FIFO (first in first out) order.

But how will Call Stack know, that there are some pending operations in a callback queue? 🤔

Event Loop

DriftBossGIF.gif

The event loop is just like a manager who keeps checking with Call Stack and Event Queue. It checks if the call stack is empty, it goes into the Event/Callback queue to check if there are any pending tasks available. If yes, it takes those tasks one by one and puts them onto the call stack until the queue gets empty.

Basic Architecture

event-loop.gif

Basic Example

Let’s take an example and see what happens when we’re running the following code

const foo = () => console.log("First");
const bar = () => setTimeout(() => console.log("Second"), 500);
const baz = () => console.log("Third");

bar();
foo();
baz();

Output:
First
Third 
Second

1_7coLKNPemPd9o40PmUvuvQ.gif

  1. We invoke bar() -> bar() returns a setTimeout function.
  2. The callback we passed to setTimeout gets added to the Web API, and the setTimeout function and bar() get popped off the callstack.
  3. The timer runs, in the meantime foo() gets invoked and logs First. foo() returns (undefined), baz() gets invoked, and the callback gets added to the queue.
  4. baz() logs Third.
  5. The event loop sees the callstack is empty after baz() returned, after which the callback gets added to the call stack.
  6. The callback logs Second.