The mighty "Event Loop"

The mighty "Event Loop"

ยท

3 min read

If you have some experience with JavaScript you would have surely heard the word "Event Loop". Event Loop is an important concept of javascript language and interviewers' favorite question.

Javascript is synchronous, blocking in nature.

Javascript is a single-threaded language.

js-single-threaded.png

Asynchronous Code Execution

We know that Javascript can perform asynchronous tasks giving us the illusion of multi-threading. Let's have a look at what happens behind the scene.

When an async function like setTimeout is called it is handed off to the browser. which uses multi-thread. The code execution continues making javascript act as non-blocking and asynchronous language. The code execution continues and the call stack which is responsible for keeping track of the operations to be executed starts to build up.

Event Loop, Queue, and Async Code

event-loop.png

Here in the above example, you can see that the setTimeout function is handed off to the browser. In the stack, the function greet() is sent and is popped out after its execution. Now the stack becomes empty. The setTimeout is sent to the message queue after a specified time and it waits there until the stack is empty and then pushes it into the stack.
The event loop facilitates this process; it constantly checks whether or not the stack is empty. If it is empty, new functions are added from the message queue. If it is not, then the current function call is processed.

Thus, JavaScript is single-threaded and browser API uses multiple threads giving asynchronous nature to Javascript.

Wrap Up

I hope you liked the content, there's more on the way. Stay Tuned! ๐Ÿ”ฅ
If you have any suggestions or questions or found this article helpful, please let me know in the comments.

ย