What Is Event Loop In JavaScript?
JavaScript's runtime model is fundamentally based on the event loop, a powerful mechanism responsible for the proper execution of code. This model is what enables JavaScript to exhibit its asynchronous and non-blocking behavior, making it highly efficient for tasks such as handling I/O operations, user interactions, and network requests.
Key Components
As shown in the above diagram, the Event Loop consists of the Call Stack, Web Browser, Micro Task Queue, and Macro Task Queue.
When a function is called, it gets pushed onto the call stack, and when the function returns, it gets popped off the call stack. However, when a function like setTimeout()
is called, it cannot be handled by JavaScript alone because it is a web-browser API provided by the Web Browser. So, JavaScript sends these APIs to the Web Browser for execution and continues to execute the remaining code. The Web APIs sent to the Web Browser are placed in the Micro Task Queue or Macro Task Queue according to their functions, such as Promise handlers and async/await are placed in Micro task queue and time Functions are placed on the Macro task queue
When JavaScript executes the code, the event loop checks if there is any remaining code in the task queues. If there is code remaining, the event loop processes it according to the priority of the task queue (the micro task queue has higher priority than the macro task queue).
Now, let's fully understand the concept of the event loop with the given diagram.
First, JavaScript will print "Start".
The second and third functions are web APIs and are placed in the task queue. The promise handlers will be placed in the micro task queue, and the setTimeout() function will be placed in the macro task queue.
Then, JavaScript will print the last line, "End".
Now, the event loop will check if there is any code remaining in the task queue.
First, it will process the code in the micro task queue, and then the code in the macro task queue.
So, the final output of our code will be:
"Start"
"End"
"Promise"
"Timeout"
Subscribe to my newsletter
Read articles from Anish sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by