JavaScript Event Loop
We will see what it is and how it works the event loop inside JavaScript.
JavaScript is a single-thread programming language. That means it can only run a single task at a time, but there are a few things to remember.
For talking about event loop, we must talk about call stack, web APIs and task queue earlier. We are going to start talking about call stack.
What is the call stack?
JavaScript Call Stack is the stack the JavaScript engine uses to run the code tasks as a single thread. The code is stacked one above another until all synchronous code has been executed entirely, and the call stack becomes empty. We can see it in this example:
The Call Stack ended up as follows:
The call stack becomes empty when the JavaScript engine has run all code from up to bottom of the call stack.
What are Web APIs?
JavaScript is executed in browsers. They have web APIs, such as setTimeout runners, fetch API requests, listeners, etc. They allow running tasks asynchronously. To see the behaviour in the best way, first, we will talk about task queue and event loop.
What is a task queue?
It is a queue where callbacks produced by web APIs are stacked. When web APIs run and end up tasks, we submit callbacks to this task queue.
What is an event loop?
It is the one overseeing the task queue and call stack. If there are tasks in the task queue and it considers the call stack empty, we grab the first task on the line and submit it to run to the call stack. All functions placed in the call stack are executed synchronously, but as we can see, the tasks in the task queue are asynchronously performed because they are not executed until the call stack is empty.
I hope you enjoyed the article.
Join my weekly newsletter, where I share articles to help you become a better front-end developer. You'll receive them directly to your inbox.
Here, I share a helpful video by Philip Roberts that also talk about this topic. I strongly recommend it:
If you have any questions, feel free to contact me on LinkedIn, Edi Rodriguez, or leave a comment in the post.
See you in the next post.
Have a great day!