What is event loop in NodeJS?

People get very confused with this question, whenever they try to understand the event loop in nodejs. So today I will attempt to make it as simplified as I can, So that you don’t have to worry about that much in future.

Event loop in NodeJs is a set of phases through which your application/control flow of your application passes through. Lets look into the picture to better understand this concept.

NodeJS event loop

As you can see in above diagram, NodeJS Event loop has three main phases.

  1. Timer Phase – It handles setInterval and setTimeout APIs
  2. Poll Phases (epoll in linux) – It Handles Networking or file reading calls
  3. Check phase – It handles setImmediate APIs

So what happens when you execute a simple program?

You NodeJS Process starts and executes line 1 and outputs “A” to console. Then line 2 is executed as it is a Node API, its task(handler) is pushed into timer phase with timeout as 0 seconds(Note handler is not executed). After that line 3 is executed and “C” is printed on console.

As there is no code pending, programs control flow is passed to event loop, which is first phase of event loop(timers phase). As there are one timer in this phases pushed by “line 2” and it has expired, so its handler is pushed into call stack where it will be executed by javascript runtime and “B” will be printed on console.

After that control flow is passed to POLL phase, where it finds nothing(as we have not performed any networking or file operation), so it skips the POLL phase and goes to check phases and finally exists the programs as there are no pending timers.

Thanks for reading.

Leave a Reply