Getting Started With Node – Course

How Event Loop Works

Let’s refer to the diagram from the last lesson.

Single threading system

As you can see in the diagram, I/O does not get blocked by any thread in Node.js. Then, how does it notify to particular processes that the task has been done or an error has occurred?

We will look at this in detail in this lesson.

Importance of event loop

Node.js is asynchronous in nature and you need to program it in an asynchronous way, which you cannot do unless you have a clear understanding of the event loop.

If you know how the event loop works, you will no longer get confused and hopefully, never block the event loop.

How Event Loop Works

The Node.js runtime system has an execution stack, where it pushes every task that it wishes to execute. Operating system pops the task from the execution stack and conducts the necessary action required to run the task.

To run the asynchronous code, this approach won’t work. The libuv library introduces a queue that stores the callback for each asynchronous operation.

Event loop runs on a specific interval, which is called tick in the Node.js terminology, and check the stack. If the stack is empty, it takes the callback from the queue and pushes it in the stack for execution, as shown in the following figure:

How event loop works

The libuv library creates the thread and returns the callback to us. As it’s an asynchronous operation, it goes to the queue instead of the stack and the event loop fetches it when the stack is empty and does the execution.

You can validate the same concept using the setTimeout() function.

Consider the following code:

   console.log("i am first");
   setTimeout(function timeout() {
     console.log("i am second");
}, 5000);
console.log("i am third");

If you run the previous code, you will get an output similar to the following:

   i am first
   i am third
   i am second

The reason is obvious, setTimeout() waits for five seconds and prints its output; however, that does not block the event loop.

Let’s set the timer to 0 seconds and see what happens:

console.log("i am first");
   setTimeout(function timeout() {
     console.log("i am second");
}, 0);
   console.log("i am third");

The output is still the same:

   i am first
   i am third
   i am second

Why so? Even if you set the timer to 0, it goes in the queue; however, it is immediately processed as its time is 0 second. The event loop recognizes that the stack is still not empty, that is, the third console was in process; therefore, it pushes the callback after the next tick of the event loop.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.