...

/

Blocking vs. Non-blocking Mode

Blocking vs. Non-blocking Mode

Learn about event loops, their disadvantages, and their mechanism in JavaScript and Node.js.

Previously, we studied that in an event loop architecture, everything happens on a single thread.

Take, for instance, reading a file. In a blocking environment, we would read the file and have the process waiting for it to finish until we execute the next line of code. While the operating system is reading the file’s contents, the program is in an idle state, wasting valuable CPU cycles:

const result = readFile('./README.md');
// Use result
Read a file in a blocking environment

The program will wait for the file to be read, and only then will it continue executing the code.

The same operation using an event loop would trigger the “read the file” event and execute other tasks (for instance, handling other requests). When the file reading operation finishes, the event loop will call the callback function with the result. This time, the runtime uses the CPU cycles to handle other requests while the OS retrieves the file’s contents, making better use of the resources:

const result = readFileAsync('./README.md', function(result) {
// Use result
});
Read file with an event loop

In the example above, the task gets a callback assigned to it. When the job is complete (this might take seconds or milliseconds), it calls back the function with the result. When this function is called, the code inside runs linearly.

Why aren’t event loops used more often?

Now that we understand the advantages of event loops, this is a very reasonable question. One of the reasons event loops ...