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:

  1. The first, second, third, and fourth functions are defined.

  2. The code execution starts from the top, and the first function is called. It is added to the call stack.

  3. The console.log("First function") statement inside the first function is executed, logging "First function" to the console. The first function is then removed from the call stack.

  4. The code execution moves to the next line and calls the second function. It is added to the call stack.

  5. The console.log("Second function") statement inside the second function is executed, logging "Second function" to the console. The second function is removed from the call stack.

  6. The code execution continues to the next line and calls the third function. It is added to the call stack.

  7. The setTimeout function is called inside the third 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. The setTimeout 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.

  8. The third function is removed from the call stack, and the code execution moves to the next line, calling the fourth function. It is added to the call stack.

  9. The console.log("Fourth function") statement inside the fourth function is executed, logging "Fourth function" to the console. The fourth function is removed from the call stack.

  10. At this point, all synchronous code execution is complete, and the call stack is empty.

  11. Meanwhile, the timer set by setTimeout completes after approximately 2000 milliseconds. The web API notifies the event loop about the completion of the timer.

  12. The event loop places the callback function (the arrow function passed to setTimeout) onto the callback queue.

  13. 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.

  14. The arrow function from setTimeout is added to the call stack.

  15. 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.

  16. The event loop checks the callback queue again and finds it empty.

  17. 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.

Contact me: Twitter Github

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

youtube.com/watch?v=8aGhZQkoFbQ