How JavaScript Works: Web APIs, Callback Queue, and Event Loop

How JavaScript Works: Web APIs, Callback Queue, and Event Loop

Hello everyone ๐Ÿ‘‹, I hope you are doing great.

So, In the previous article, we learned about Google’s V8 Engine, Heap Memory, and Call Stack.

In this article, we will learn about Web APIs, Callback Queue, and Event Loop.

๐ŸŒ Web APIs

The Web APIs are provided by the web browser that gives additional functionality to the V8 engine.

The Web API calls are added to the Web API Container from the Call Stack. These Web API calls remain inside the Web API Container until an action is triggered. The action could be a click event or HTTP request, or a timer finishes its set time. Once an action is triggered, a callback function is added to the Callback Queue.

๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘ Callback Queue

The Callback Queue is a FIFO data structure.

The Callback Queue stores all the callback functions in the order in which they are added.

โ™ป๏ธ Event Loop

What happens when you have function calls that take a large amount of time to execute in the Call Stack?

For example

  • Executing a for loop from 1 to 10B
  • Making a network request
  • Doing image processing

Let’s take an example.

Synchronous Code Visualization

You may ask why this is a problem? The problem is when the Call Stack has a function to execute, the browser cannot do anything else because it is blocked.

The solution is an asynchronous callback, promises, and async / await.

Let’s take an example.

Asynchronous Code Visualization

The Event Loop has only one simple job to do. It looks at the Call Stack and Callback Queue, if the Call Stack is empty, it pushes the first callback function of the Callback Queue to the Call Stack..

I hope now you have a good understanding of how JavaScript works.

In the next article, we will learn how V8 compiles our JavaScript code.

๐Ÿ“š Resources

What the heck is the event loop anyway? | Philip Roberts | JSConf EU

Thanks for reading! My name is Bipin Rajbhar; I love helping people to learn new skills ๐Ÿ˜Š. You can follow me on Twitter if youโ€™d like to be notified about new articles and resources.

Leave a Reply

Your email address will not be published.