The Node.js Event Loop

The event loop is one of the key aspects to know about the Node.js. It explains how node.js can be asynchronous and have non-blocking input and output operations. The node.js JavaScript code runs on a single thread. There is only one thing happening at a time. This limitation is very helpful and it simplifies the coding without worrying about the concurrency issues. Only thing is to avoid anything like synchronous network calls or infinite loops.

The blocking can be happened when a JavaScript code takes too long to return back control to the event loop and it can even block the UI thread and users cannot even click or scroll.

As most of the I/O primitives of JavaScript are non-blocking being blocking is the exception and this is why JavaScript is mostly based on callbacks, promises and async/await.

The call stack is a Last-In-First-Out (LIFO) stack. The event loop checks the call stack continuously to see if there is any function to be executed. These function calls are added to the call stack and executed each one in order.

example1

When this code executes, first foo() is called. inside foo() we first call bar() and then baz() is called.

At this point the call stack looks like this:

call stack

The event loop on every iteration looks if there is something in the call stack and executes it until the call stack is empty.

The above example looks normal. Let’s see what happens when the setTimeout(() => {},0) function is executed. It is used to call a function, but execute it once every other function in the code has executed.

Look at the following example.

example2

It gives the following output maybe surprisingly.

When this code runs first foo() is called. Inside foo() we first call setTimeout, passing bar as an argument, and we instruct it to run immediately as fast as it can, passing 0 as the timer. Then we call baz().

What actually happens here?

The browser or the node.js starts the timer when setTimeout() is called. Once the timer expires as we put 0 as the timeout, the callback function is put in the message queue.

The message queue is also where the user-initiated events like click or keyboard events or fetch responses are queued before the code has the opportunity to react to them.

The loop gives priority to the call stack and processes everything found in the call stack and once there’s nothing in there, loop pick ups things in the message queue.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store