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.
Top comments (4)
I have a question . So the event loop and callback queue are provided in v8? Or the browser has provided it as a web api
Browser
Yes it is provided by the browser but not as a Web API. The event loop is also provided by Node server side. Both Node and the browser are Javascript runtimes based on V8.
Node's event loop works differently.