Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 3, 2020 07:52 am GMT

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
blocking

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
blocking

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 youd like to be notified about new articles and resources.


Original Link: https://dev.to/bipinrajbhar/how-javascript-works-web-apis-callback-queue-and-event-loop-2p3e

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To