loading...
Cover image for How JavaScript Works: Web APIs, Callback Queue, and Event Loop

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

bipinrajbhar profile image Bipin Rajbhar ・2 min read

How JavaScript Works (2 Part Series)

1) How JavaScript Works: An Overview of JavaScript Engine, Heap, and Call Stack 2) 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 you’d like to be notified about new articles and resources.

How JavaScript Works (2 Part Series)

1) How JavaScript Works: An Overview of JavaScript Engine, Heap, and Call Stack 2) How JavaScript Works: Web APIs, Callback Queue, and Event Loop

Posted on May 3 by:

bipinrajbhar profile

Bipin Rajbhar

@bipinrajbhar

I love to share every thing that i have learned

Discussion

markdown guide