DEV Community

ricahcyuzuzo
ricahcyuzuzo

Posted on • Edited on

My Understanding of Event loop in Nodejs

The understanding of event loop in Nodejs will first have to start with Knowing about the Threads, The thread can be seen as the a unit of operations the CPU has to do for us. One single program process can contain many Threads.

Using the below image to get an idea about the threads.

Alt Text

The Event Loop

When you run a node program, automatically the thread is created, That thread is the place where the codebase is going to be executed, In that thread, 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.

Note This: the event loop does not get generated instantly as soon as we run our program. It only runs once the whole program has been executed

Let me explain in details

I will just have to assume that I have a program file to run in Nodejs 'programFile.js'.

We can run 'node programFile.js'.

The This is, in order to understand what is being done by the event loop, the picture below is showing how things are going during the event loop tick.

Alt Text

Step1: PerformChecks

has a specific condition that will determine if the loop needs to iterate again or not. Every iteration of the event loop is called a tick.

Conditions for Event loop to do a tick.

we execute our program, we will have a series of operations that need to be performed. These operations can be split into three main types:

  • Pending timer operations (setTimeout(), setInterval(), setImmediate())
  • Pending operating system tasks
  • Pending execution of long running operations

So, whenever one of those are pending the event loop will perform a new tick!

Step 2: Performing a tick

For every loop iteration, we can distinguish the following phases:

Phase 1: Node looks at its inner collection of pending timers and checks which callback functions passed to setTimeout() and setInterval() are ready to be called in case of an expired timer.

Phase 2: Node looks at its inner collection of pending OS tasks and checks which callback functions are ready to be called. An example of this could be the completed retrieval of a file from our machine’s hard drive.

Phase 3: Node pauses its execution waiting for new events to occur. With new events, we include: a new timer completion, a new OS task completion, a new pending operation completion.

Phase 4: Node checks if any function related to pending timers related to the setImmediate() function are ready to be called.

Phase 5: Manage close events, used to clean the state of our application.

                                --End--

Top comments (0)