Do you know JS event loop ? ”Skip” : ”Read this article”
Note: This article builds upon the concepts discussed in my previous article on the call stack. If you haven’t read it yet, you can find it here.
Before diving into the event loop, let’s briefly recap our JavaScript knowledge. JavaScript is a single-threaded language, which means it can only execute one task at a time. In other words, if multiple tasks are requested, JavaScript can only handle them one by one. However, in today’s fast-paced world, this sequential execution can be limiting, especially when it comes to responsive web applications. This is where Web APIs come into play. Web APIs, such as the DOM API and HTTP requests, are provided by the browser and are separate from the JavaScript engine.
Now, let’s discuss the event loop. The event loop is a mechanism in JavaScript that addresses the limitations of being single-threaded. It manages the execution of asynchronous code and ensures efficient operation without blocking the main thread.
When JavaScript encounters asynchronous operations, like setTimeout, HTTP requests, or other asynchronous functions, it delegates their execution to the browser’s Web APIs. These operations are performed independently in the background, separate from the main JavaScript thread.
Once an asynchronous operation is completed, its corresponding callback function is placed in a queue called the “callback queue.” The event loop continuously monitors both the call stack and the callback queue. When the call stack is empty, indicating that all synchronous operations have been completed, the event loop checks the callback queue. If there is a callback function in the queue, it takes that function and pushes it onto the call stack for execution.
Now, let’s understand the event loop step-by-step examining the following code:
const first = ()=> console.log("First function");
const second = ()=> console.log("Second function");
const third = ()=> setTimeout(() => console.log("Third function"), 2000);
const fourth = ()=> console.log("Fourth function");
first();
second();
third();
fourth();
Before explaining it figure out by yourself. What are the console results?
A) First function
Second function
Third function
Fourth function
B) First function
Second function
Fourth function
Third function
C) First function
Third function
Fourth function
Second function
D) First function
Third function
Second function
Fourth function
If your answer is B, it’s correct! Let’s understand why it is:
The
first
,second
,third
, andfourth
functions are defined.The code execution starts from the top, and the
first
function is called. It is added to the call stack.The
console.log("First function")
statement inside thefirst
function is executed, logging "First function" to the console. Thefirst
function is then removed from the call stack.The code execution moves to the next line and calls the
second
function. It is added to the call stack.The
console.log("Second function")
statement inside thesecond
function is executed, logging "Second function" to the console. Thesecond
function is removed from the call stack.The code execution continues to the next line and calls the
third
function. It is added to the call stack.The
setTimeout
function is called inside thethird
function. It is a web API provided by the browser environment, allowing us to schedule a function to be executed asynchronously after a specified delay. ThesetTimeout
function sets up a timer and returns immediately. It does not block the execution of the code. The timer is set for a delay of 2000 milliseconds.The
third
function is removed from the call stack, and the code execution moves to the next line, calling thefourth
function. It is added to the call stack.The
console.log("Fourth function")
statement inside thefourth
function is executed, logging "Fourth function" to the console. Thefourth
function is removed from the call stack.At this point, all synchronous code execution is complete, and the call stack is empty.
Meanwhile, the timer set by
setTimeout
completes after approximately 2000 milliseconds. The web API notifies the event loop about the completion of the timer.The event loop places the callback function (the arrow function passed to
setTimeout
) onto the callback queue.The event loop continuously checks if the call stack is empty. When it detects an empty call stack, it takes the next task from the callback queue and pushes it onto the call stack for execution.
The arrow function from
setTimeout
is added to the call stack.The
console.log("Third function")
statement inside the arrow function is executed, logging "Third function" to the console. The arrow function is removed from the call stack.The event loop checks the callback queue again and finds it empty.
Since there is no more code to execute, the program terminates.
Code result:
First function
Second function
Fourth function
Third function
By utilizing this event loop mechanism, JavaScript ensures that asynchronous operations are handled efficiently, without blocking the main thread. This enables the browser to remain responsive and perform other tasks while waiting for asynchronous operations to complete.
I hope this explanation clarifies the concept of the event loop for you. Let me know if you have any further questions or if there’s anything else you’d like me to add to the article.
Resources:
developer.mozilla.org/en-US/docs/Web/JavaSc..
✨♻️ JavaScript Visualized: Event Loop
*Oh boi the event loop. It's one of those things that every JavaScript developer has to deal with in one way or another…*dev.to