Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (2024)

NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications.

Asynchronous here refers to all those functions in JavaScript that are processed in the background without blocking any other request.

In this article, you will learn and understand how NodeJS works and handles all functions or requests sent to a server either synchronously or asynchronously.

What is an Event Loop?

You might have guessed it right – Node handles requests using an Event loop inside the NodeJS environment. But first, let's understand some basic terms which will help us understand the whole mechanism.

An event loop is an event-listener which functions inside the NodeJS environment and is always ready to listen, process, and output for an event.

An event can be anything from a mouse click to a keypress or a timeout.

What are Synchronous and Asynchronous programming?

Synchronous programming means that the code runs in the sequence it is defined. In a synchronous program, when a function is called and has returned some value, only then will the next line be executed.

Let's understand with this an example:

const listItems = function(items) { items.forEach(function(item) { console.log(item) })}const items = ["Buy milk", "Buy coffee"]listItems(items)
The output will look like this:"Buy milk""Buy coffee"

In this example, when the listItems(items) function is called, it will loop through the array of items. The console.log(item) function gets called first for the first item of the array and it prints "Buy milk". Then again console.log(item) gets executed and this time it passes the second item of the array and prints "Buy coffee".

So you can say that the function was executed in the sequence it was defined.

Asynchronous programming, on the other hand, refers code that doesn't execute in sequence. These functions are performed not according to the sequence they are defined inside a program but only when certain conditions are met.

For example, setTimeOut() performs a task after a delay of a certain predefined number of miliseconds.

setTimeOut(function(){ return( console.log("Hello World!") )}, 3000)

These functions do not run line by line but only when they are required to run, irrespective of the function's declaration. In this case, the function runs automatically after 3 seconds when all synchronous functions have been executed.

Note: Asynchronous functions will run and execute only after all the synchronous functions have been executed. Until then, they will be processed in the background.

If you want to learn more about NodeJS and asynchronous programming, you can refer to this article

But, how does NodeJS handle asynchronous functions in the background and run all synchronous functions first? All these mechanisms can be easily explained with the NodeJS event loop.

How Does an Event Loop Work?

Now let's see how NodeJS event loops can execute a simple synchronous program using a Nodejs event loop diagram. Then we'll examine how Node executes the program line by line.

As we go through this section you'll start to understand what you are seeing here:
Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (1)

In the top-left corner, you have a Node file that is going to get executed. At the bottom left, you have an output terminal for the program. Then you have Call stack, Node APIs and Callback queue. All these together constitute the NodeJS environment.

For synchronous programming, you only need to focus on the call stack. This is the only part of the NodeJS environment that will be working in this case.

A callback stack is a data structure that you use to keep track of the execution of all functions that will run inside the program. This data structure has only one open end to add or remove top items.

When the program starts executing, it first gets wrapped inside an anonymous main() function. This is automatically defined by NodeJS. So main() gets pushed first to the callback stack.

Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (2)

Next, the variables a and b are created and their sum is stored in a variable sum. All these values are stored in memory.

Now, the console.log() is a function that is called and pushed inside the callback stack. It gets executed and you can see the output on the terminal screen.

Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (3)

After this function gets executed, it is removed from the callback stack. Then the main() is also removed as nothing is left to be called from the program. This is how a synchronous program gets executed.

Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (4)
Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (5)

Now, let's see how asynchronous functions or programs get executed inside NodeJS. We need the callback stack, Node APIs and callback queue all together to process an asynchronous function.

Let's start by looking at this example:

Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (6)

As usual, when the program starts executing, first the main() function gets added to the callback stack. Then console.log("Start") is called and added to the callback stack. After processing, the output is visible on the terminal and then it gets removed from the callback stack.

Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (7)
Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (8)

Now the next is the setTimeOut(...Zero...) function which gets added to the callback stack.

As this is an asynchronous function, it will not get processed in the callback stack. It is then added from the callback stack to the Node APIs where an event is registered and a callback function is set to get processed in the background.

Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (9)
Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (10)

Next is the setTimeOut(...Two..) which also gets added to the Node API from the callback stack as it is an asynchronous function. Then another callback function gets set to be processed after a 2 second timeout in the background. Up until this point other functions can be performed.

This is called non-blocking behaviour where all the synchronous functions are processed and executed first and asynchronous functions are processed in the background while waiting their turn to get executed.

Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (11)
Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (12)

Next, the console.log("End") function is called at last in the callback stack and gets processed here. You can see the output on the terminal. Now, all the synchronous functions are processed, and main() is removed from the callback stack.

In the background, all the asynchronous functions get processed and their callbacks are stored in the callback queue. The one which is processed first will be added first in the queue for execution in the callback stack.

Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (13)
Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (14)
Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (15)

Note: Asynchronous functions cannot run inside a callback stack until it gets emptied. That means that after main() is removed from call stack, only then can all asynchronous functions start executing.

Now, one by one they are pushed to the callback stack using the event loop and finally get executed. Each of the callback functions will print the value with the console.log() function getting called each time.

Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (16)

At last, these are also removed after being executed and now the callback stack is empty.

Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (17)

This is how NodeJS will execute synchronous and asynchronous funtions inside the environment and how the event loop manages to call asynchronous functions.

Conclusion

In this article, you learned the internal working of NodeJS and saw how asynchronous programs get executed.

Now you should understand why the two second time delay function does not block the rest of the program from executing. You also know why the zero second delay function prints the value at last after "End" prints.

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

Event Loops in NodeJS – Beginner's Guide to Synchronous and Asynchronous Code (2024)

FAQs

How does Node.js handle asynchronous operations and what is the event loop? ›

Node. js has two types of threads: one Event Loop and k Workers. The Event Loop is responsible for JavaScript callbacks and non-blocking I/O, and a Worker executes tasks corresponding to C++ code that completes an asynchronous request, including blocking I/O and CPU-intensive work.

How would you explain the event loop to a beginner? ›

The event loop waits for the function stack to be empty, once the call stack is empty this will push the first function from the event queue to the call stack, and in this way, the desired function will be called.

What is asynchronous and event driven node JS? ›

Back to the definition from Node's website: Node is an asynchronous event driven JavaScript runtime. In this context asynchronous means that when you write your code you do not try to predict the exact sequence in which every line will run.

What is the event loop flow in JavaScript? ›

An event loop is a looping algorithm or we can say a job scheduling algorithm that schedules the events based on the priorities of the task and then executes it. This algorithm makes use of a queue data structure for scheduling the tasks and then it uses a stack data structure called Call stack for executing the tasks.

How does event loop handle async code? ›

The Event Loop is important because it allows JavaScript to execute code asynchronously. This means that JavaScript can continue running even while asynchronous tasks are in progress. This makes it possible to create responsive and efficient web applications.

What is event loop in asynchronous programming? ›

The event loop plays a pivotal role in orchestrating these asynchronous operations, ensuring they run smoothly and efficiently without causing the dreaded “blocking” that can slow down applications and websites.

How do you explain an event loop in node JS? ›

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. Since most modern kernels are multi-threaded, they can handle multiple operations executing in the background.

What are the 6 phases of event loop? ›

Understand how the event loop in Node. js works, as well as the actions, or "macro-tasks", being executed during each of its six phases: timers, I/O callbacks, preparation / idle phase, I/O polling, setImmediate() callbacks execution, and close events callbacks.

How does the event loop work in node JS? ›

An event loop is an endless loop, which waits for tasks, executes them, and then sleeps until it receives more tasks. The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task. The event loop allows us to use callbacks and promises.

Why Node.js is synchronous? ›

JavaScript is synchronous by default and is single threaded. This means that code cannot create new threads and run in parallel. But JavaScript was born inside the browser, its main job, in the beginning, was to respond to user actions, like onClick , onMouseOver , onChange , onSubmit and so on.

How does Node.js handle asynchronous programming? ›

Callbacks are a fundamental mechanism in Node. js for handling asynchronous operations. A callback is a function that is passed as an argument to another function and gets executed once the operation completes. This allows for the continuation of code execution without blocking.

How does Node.js handle asynchronous? ›

Callbacks are the traditional way of handling asynchronous operations in Node JS. A callback function is passed as an argument to an asynchronous function and is executed when the operation completes.

Why do we need an event loop? ›

In JavaScript, the event loop is a fundamental mechanism that enables the asynchronous execution of code. It's an essential part of the JavaScript runtime environment, allowing the language to handle non-blocking operations efficiently.

What is the purpose of an event loop? ›

JavaScript has a runtime model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks. This model is quite different from models in other languages like C and Java.

What is the difference between event loop and node JS? ›

In summary, the JavaScript event loop and the Node. js event loop are both important programming constructs that enable asynchronous programming in JavaScript. While the JavaScript event loop is built into the browser's rendering engine and is single-threaded, the Node. js event loop is built into Node.

How does Node.js handle asynchronous operations? ›

Callbacks are the traditional way of handling asynchronous operations in Node JS. A callback function is passed as an argument to an asynchronous function and is executed when the operation completes.

How does Node.js use asynchronous programming? ›

Asynchronous programming enables efficient handling of concurrent operations, allowing web applications to scale effectively. By leveraging non-blocking I/O operations, web servers built on asynchronous frameworks like Node. js can handle thousands of simultaneous connections without consuming excessive resources.

How does the event loop handle asynchronous callback functions? ›

Source: https://www.javatpoint.com/javascript-call-stack

js runtime environment, allowing the Event Loop to continue processing other tasks. Once the asynchronous operation completes, the associated callback is placed in the Callback Queue, awaiting the Event Loop's attention for execution.

Top Articles
Latest Posts
Article information

Author: Pres. Carey Rath

Last Updated:

Views: 6174

Rating: 4 / 5 (41 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Pres. Carey Rath

Birthday: 1997-03-06

Address: 14955 Ledner Trail, East Rodrickfort, NE 85127-8369

Phone: +18682428114917

Job: National Technology Representative

Hobby: Sand art, Drama, Web surfing, Cycling, Brazilian jiu-jitsu, Leather crafting, Creative writing

Introduction: My name is Pres. Carey Rath, I am a faithful, funny, vast, joyous, lively, brave, glamorous person who loves writing and wants to share my knowledge and understanding with you.