Event loop in Node js

Dipak Belsare
Dec 7, 2021 · 3 min read
Image from Packt youtube

Introduction

In this tutorial, you will learn what is Event loop is in node js, how the Event Loop in Node.js works, as well what actions are being executed during each of its phases.

What is an event loop in Node.js?

The event loop allows Node.js to perform non-blocking I/O operations despite the fact that JavaScript is single-threaded. It is done by assigning operations to the operating system whenever and wherever possible.

Whenever we run a Node program, a thread is automatically created. This thread is the only place where our entire codebase is going to be executed. Inside of it, something called the event loop is generated. The role of this loop is to schedule which operations our only thread should be performing at any given point in time.

Features of Event Loop:

Event Loop Explanation

When Node.js starts, it initializes the event loop, processes the provided input script (or drops into the REPL, which is not covered in this document) which may make async API calls, schedule timers, or call process.nextTick(), then begins processing the event loop.

Phases of Event Loop

Between each run of the event loop, Node.js checks if it is waiting for any asynchronous I/O or timers and shuts down cleanly if there are not any.

Example

console.log("This is the first statement");setTimeout(function(){     console.log("This is the second statement");}, 2000);console.log("This is the third statement");

When you execute the above code, you will see the following output:

This is the first statement
This is the third statement
This is the second statement

Conclusion

In this article, you learned the event loop in the node js and Event Loop phases in detail.

That’s all! I hope you enjoyed reading this article and learned something new. Do share this article if you find it useful.

nonstopio

A Bespoke Engineering Studio