14 Tweets 9 reads Aug 09, 2023
Event loop is a confusing concept in JavaScript.
You can better understand code execution if you understand it.
Here's everything you need to know about it:
Before diving into it, we need to understand what multithreading is.
Multithreading is nothing but a programming feature by which we can make maximum use of the CPU by running two or more parts of the program simultaneously.
What exactly event loop is?
It's a mechanism that allows JavaScript to handle multiple tasks concurrently without blocking the main execution thread.
JavaScript is a single-threaded language.
It executes one piece of code at a time in a sequence. However, many tasks in web development are asynchronous. For ex, fetching data from a server.
The event loop is made up of two data structures:
1. Stack
2. Queue
Call stack
It keeps all the operations in order which has to be executed. After the successful execution of an operation, it is popped out.
Event Queue
It is responsible for sending new functions to the call stack for processing. It follows the queue data structure to maintain the correct sequence in which all operations should be sent for execution.
Let's try to visualize it. Consider the following code and output:
As you can see, one, two, and three is being printed out as they appeared in the code in serial order.
But now consider this piece of code:
The output in this particular case is,
one
three
two
Why did this happen?
Web API
This is where the browser API or web API comes into play. These APIs are pre-built into the browsers.
Whenever an async function comes in call stack, it is sent to web API which waits for the specified time to send this operation back to the event queue.
So, setTimeout function was sent to web API, which waited there for the specific time period and after that it was sent to the queue for processing
That's why the output of the above code is,
one
three
two
These three components — call stack, event queue, and web APIs make a cycle which is known as an event loop.
As simple as that, With that being said. This is the end of this thread. Follow @PrathKum for more amazing content.
Peace out! 😉

Loading suggestions...