The Event Loop

Understand the inner workings of the Event Loop.

Concurrency

While we have praised Node.js for running applications on a single thread, there is more to it. When we ask the OS to read a file for us, we use the file system API. Node.js provides us with several APIs that allow us to make asynchronousprocesses that can run in the background without causing the main program to wait calls. For Node.js, these underlying APIs are written in C++ and threads are hidden from us. If you have ever worked with threads before, you will realize that things can get messy when dealing with multiple threads. Deadlocks and race conditions are the worst, so having Node.js manage that for us is, undoubtedly, a praiseworthy feature.

How does it work?

Let’s take a look at the components that make all of this possible.

Event loop

The event loopThe event loop is the backbone of Node.js. It solves the problem of multi-threading is initialized when Node.js runs. It can perform otherwise blocking operations in a non-blocking manner. The event loop can be further broken down into phases, but that is beyond the scope of this course.

svg viewer

Event queue

The event queue stores incoming events in an orderly fashion. It then passes those events one-by-one to the event loop.

svg viewer

API pool

The API pool consists of all the APIs that Node.js provides to execute blocking events asynchronously.

svg viewer

In action

Let’s see how Node.js handles functions that take time to process, like setTimeout. setTimeout is used to execute a function after a set amount of time. The first argument is the function, which, in our case, is the lateFunc. The second argument is the time in milliseconds. If lateFunc were to take arguments, they would then be passed after the second argument. Here is an example:

function lateFunc() {
    console.log('This was done asynchronously!');
}

console.log('This is the first log');

setTimeout(lateFunc, 5000);

console.log('This is the second log');
Hit the RUN button to view the output

Try changing the timeout duration of the setTimeout function to see how the output changes.


Let’s see what Node.js is doing behind the screen.

All that glitters isn’t gold

The event loop is a fundamental part of Node.js and is the secret to its efficiency. However, Node.js is still limited by the amount of processing power it can harness. Complex programs that require a lot of processing significantly can slow things down. While Node.js can handle asynchronous I/OInput/Output functions with ease, it is not suitable for compute-intensive applications like machine learning. Hence, it is essential to weigh the pros and cons before choosing a framework or a runtime environment.

Create a free account to view this lesson.

Continue your learning journey with a 14-day free trial.

By signing up, you agree to Educative's Terms of Service and Privacy Policy