The Event Loop
Understand the inner workings of the Event Loop.
We'll cover the following
Concurrency
While we have praised Node.js for running applications on a single thread, there is more to it. When we ask the OS to read a file for us, we use the file system API. Node.js provides us with several APIs that allow us to make
How does it work?
Let’s take a look at the components that make all of this possible.
Event loop
The
Event queue
The event queue stores incoming events in an orderly fashion. It then passes those events one-by-one to the event loop.
API pool
The API pool consists of all the APIs that Node.js provides to execute blocking events asynchronously.
In action
Let’s see how Node.js handles functions that take time to process, like setTimeout
. setTimeout
is used to execute a function after a set amount of time. The first argument is the function, which, in our case, is the lateFunc
. The second argument is the time in milliseconds. If lateFunc
were to take arguments, they would then be passed after the second argument. Here is an example:
function lateFunc() { console.log('This was done asynchronously!'); } console.log('This is the first log'); setTimeout(lateFunc, 5000); console.log('This is the second log');
Try changing the timeout duration of the setTimeout
function to see how the output changes.
Let’s see what Node.js is doing behind the screen.
All that glitters isn’t gold
The event loop is a fundamental part of Node.js and is the secret to its efficiency. However, Node.js is still limited by the amount of processing power it can harness. Complex programs that require a lot of processing significantly can slow things down. While Node.js can handle asynchronous
Create a free account to view this lesson.
Continue your learning journey with a 14-day free trial.
By signing up, you agree to Educative's Terms of Service and Privacy Policy