Event loop in Node JS

Event loop in Node JS

One of the most important concept of node js

Introduction

Node Js is a runtime environment for java script and java script is a synchronized single threaded language. Single threaded means only one task can run at a time. Node Js is built of 2/3 Js and 1/3 C++ . The C++ provide asynchronization features which help us run task in parallel.

Event Loop

The event loop is the major feature of node Js and is very useful for single threaded applications. It uses a stack data structure. When a JS program run it creates a Global Execution Context(GFC), which is used to execute functions and is pushed in the stack. When a function is invoked it gets pushed to the stack and is returned after completion. Since the stack is a single way, we can run multiple programs at once.

Examples

Let us consider the following piece of code,

console.log("One");

setTimeout(function(){
    console.log("Two");
}, 1000);

console.log("Three");

OUTPUT:

First
Three
Two

When the setTimeout function is called it request the timer present in the window object to run and wait for 2000 seconds but the next function statement runs first. This is due to something called the Callback queue which stores the callback functions until the time is over and allows the program to run the next line of code. After the time has completed the queue returns the callback and allow execution, with this feature fetch() and other request based operations are performed. There is also a more priority queue called micro task queue for functions involving more priority.

Did you find this article valuable?

Support hari's blog by becoming a sponsor. Any amount is appreciated!