Event Loop

An event loop is just like a while loop. It executes one command at a time and it will run until Node has executed every line of code. It has One Process, One Thread and One Event Loop.

Now, let’s take a look at how our code runs inside of Node.js instance.


console.log('Task 1');
console.log('Task 2');

// some time consuming for loop
for(let i = 0; i < 999999; i++) {
}

console.log('Task 3');

What happens when we run this code? It will first print out Task 1 than Task 2 and then it will run the time consuming by the for a loop after that it will print out Task 3.

Node puts all our tasks into an Events queue and sends them one by one to the event loop. The event loop is single-threaded and it can only run one thing at a time. So it goes through Task 1 and Task 2 then the very big for loop and then it goes to Task 3. This is why we see a pause in the terminal after Task 2 because it is running the for a loop.
Now let’s do something different. Let’s replace that for loop with an I/O event.


console.log('Task 1');
console.log('Task 2');
fs.readFile('./file.txt', (err, data) => {
    if (err) throw err;
    console.log('done reading file');
    process.exit();
});
console.log('Task 3');

Now the result is
Task 1
Task 2
Task 3
done reading file

I/O tasks, network requests, database processes are classified as blocking tasks in Node.js. So whenever the event loop encounters these tasks it sends them off to a different thread and moves on to the next task in events queue. A thread gets initiated from the thread pool to handle each blocking tasks and when it is done, it puts the result in a call-back queue. When the event loop is done executing everything in the events queue it will start executing the tasks in the call-back queue.