Event Loop | Why is this so important in Node JS?

Mahmood Nalim
5 min readSep 3, 2021

What is the Event Loop? 😎

The event loop is what allows Node. js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible.The Event Loop is one of the most important aspects to understand about Node.js.

Why is this so important? 🤷‍♂️

Because it explains how Node.js can be asynchronous and have non-blocking I/O.The Node.js JavaScript code runs on a single thread. There is just one thing happening at a time.Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for the event to occur.

Let's go to Event Loop !! 🕵️‍♂️

Call Stack :
A first in last out simple data structure. Every time we call a function it pushes to the stack and every time we return from a function it pops out of the stack.This is where all your javascript code gets pushed and executed one by one as the interpreter reads your program, and gets popped out once the execution is done.

Node Event Queue :
Sometimes it is called message queue or callback queue. The event loop pushes callbacks from the event queue to call stack. The event loop executes tasks from the event queue only when the call stack is empty.

This is where your asynchronous code gets pushed to, and waits for the execution.

Event Loop :

Then comes the Event Loop, which keeps running continuously and checks the Main stack, if it has any frames to execute, if not then it checks Callback queue, if Callback queue has codes to execute then it pops the message from it to the Main Stack for the execution.

Let's make clear Event Loop with a example:

Consider the following code: 💻

If you run the previous code, you will get an output similar to the following:

i am first
i am third
i am second

The reason is obvious, setTimeout() waits for five seconds and prints its output; however, that does not block the event loop.

Let’s set the timer to 0 seconds and see what happens:

The output is still the same:

i am first
i am third
i am second

Why so? Even if you set the timer to 0, it goes in the queue; however, it is immediately processed as its time is 0 second. The event loop recognizes that the stack is still not empty, that is, third console was in process; therefore, it pushes the callback after the next tick of event loop.

When setTimeout() is called, the Browser or Node.js starts the timer. Once the timer expires, in this case immediately as we put 0 as the timeout, the callback function is put in the Message Queue.

The loop gives priority to the call stack, and it first processes everything it finds in the call stack, and once there’s nothing in there, it goes to pick up things in the message queue.

We don’t have to wait for functions like setTimeout, fetch or other things to do their own work, because they are provided by the browser, and they live on their own threads. For example, if you set the setTimeout timeout to 2 seconds, you don't have to wait 2 seconds - the wait happens elsewhere.

Multi Thread Vs Single Thread ? 🙄

Multi-threading approach provides parallelism using threads so that multiple programs can simultaneously run. With advantages come the problems too; it is really difficult to handle concurrency and deadlock in a multi-threading system.

On the other hand, with single-threading, there is no chance of deadlock in the process and managing the code is also easy. You can still hack and busy the event loop for no reason; however, that’s not the point.

Multi Threded Server

Node.js uses single-threading for runtime environment; however, internally, it does create multiple threads for various I/O operations. It doesn’t imply that it creates threads for each connection, libuv contains the Portable Operating System Interface (POSIX) system calls for some I/O operations.

Node.JS Single Thread

If the single-threading programs work correctly, they will never block the I/O and will be always ready to accept new connections and process them.

Is Node.js single-threaded?

  • Yes! And you are right. 🤨
  • No! And You are right again. 🤔

In reality, Node.js has a V8 in it, and the code runs in the main thread where event-loop runs ( that’s why we say that it is single-threaded).

But As we know, the Node.js is not just V8. There are many APIs (C++), and all this stuff is managed by Event Loop, implemented via libuv (C++).

C++ is working in back of JavaScript code and it has access to threads. If you run the JavaScript synchronous method which has been called from Node.js, it will always run in the main thread. But if you run some asynchronous thing, it will not always run in the main thread: depending on what method you use, the event-loop can route it to one of the APIs and it can be processed in another thread.

So Is Node.js multi-threaded?

So when people ask you is Node multi- or single-threaded, you must ask a bonus question: “ When?”.

If you’ve come this far following the whole article, congratulations 😃 You are awesome.

❤ Thanks for reading and if this post was helpful, please hit the Clapp! And don’t forget to check out my other articles.

Good Luck !!

--

--