For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentIntroduction to Event Loop in Node.js: Metrics, Timers, Process

Introduction to Event Loop in Node.js: Metrics, Timers, Process

Published
06th Sep, 2023
Views
view count loader
Read it in
9 Mins
In this article
    Introduction to Event Loop in Node.js: Metrics, Timers, Process

    The event loop is a core Node.js concept. It allows you to learn about Node's asynchronous processes and non-blocking I/O. It describes the mechanisms that contribute to Node's success, power, and popularity as a modern framework.

    This lesson is excellent for Node.js developers who want a better grasp of what's going on fixed beneath of any application yet want complete control over every phase of its life cycle.  Check out Full Stack Software Development course for more information.  

    What is Node.js?

    Node.js is a framework for easily creating fast and scalable network applications that is built on Chrome's JavaScript runtime. Node.js has an event-driven, non-blocking I/O approach, making it lightweight and efficient, making it ideal for computation real-time applications running across dispersed devices. 

    Node.js is a cross-platform open-source runtime environment for creating server-side and networking applications. Node.js applications are developed in JavaScript and run on the Node.js runtime. 

    Node.js also contains a big library of JavaScript modules, that enable developing web applications using Node.js easier. 

    Node.js is influenced by and similar in design to Ruby's Event Machine and Python's Twisted. The event model is expanded in Node.js. An event loop is presented as a runtime construct rather than a library. In other systems, the event-loop is always started with a blocking call.

    At the start of a script, behaviour is set using callbacks, and at the end, a server is started using a blocking call like EventMachine::run (). There is no start-the-event-loop call in Node.js. 

    After executing the input script, Node.js just enters the event loop. When there are no more callbacks to perform, Node.js exits the event loop. The event loop is concealed from the user, similar to browser JavaScript. 

    What is an Event Loop in Node.js and How Does It Work?

    Despite the fact that JavaScript is single-threaded, Node.js uses an event loop to perform non-blocking I/O operations. 

    A thread is automatically established whenever we launch a Node program. This thread will be the sole one where our complete codebase will be run. The event loop is generated inside of it. This loop's job is to figure out which operations our single thread should be performing at any given time. 

    Most operating systems are multi-threaded, so they can handle many background tasks. The kernel tells Node.js when one of the operations is complete, as well as the callbacks linked with such an action is pushed towards the event loop, where it can be processed later. 

    Event Loop features include: 

    • This event loop is just not a loop which waits for tasks, performs them, and then rests until new ones occur.
    • The event loop executes tasks first from event queue while the call stack is empty, i.e. there are no ongoing tasks. 
    • With both the event loop, we can use callbacks and promises. 

    Example: 

    console.log("This is the first statement"); 
    setTimeout(function(){ 
    console.log("This is the second statement"); 
    }, 1000); 
    console.log("This is the third statement"); 
    Output: 

    This is the first statement 

    This is the third statement 

    This is the second statement 

    In the example above, a first console log line is pushed to the call stack, the console is logged with "This is the first statement," and the task is retrieved from the stack. The job is subsequently transmitted to the windows os, and the task's timer is established. This job is then deleted from the stack. 

    The third console log statement is then pushed to the call stack, and the console is logged with "This is the third statement," and the task is popped from the stack. 

    The callback is dispatched to the event queue when the timer set by the setTimeout function (in this example 1000 ms) expires. When the call stack is empty, the event loop takes the job at the top of the event queue and sends it to the call stack. The setTimeout function's callback function executes the instruction, logging "This is the second statement" on the console and removing the task from the stack. 

    If you are thinking of becoming full stack developer then you will need a perfect guide to get the best knowledge. You can check out Development Course online.   

    Working of Event loop

    As Node.js launches, it first organises the event loop, next processes the supplied input script, sets up timers, and thereafter begins executing its event loop. The first data script included console.log() statements and a setTimeout() feature that set a timer. 

    To conduct async operations in Node.js, a special library module called libuv is utilised. This library is also used to handle the libuv thread pool, which is managed in conjunction with Node's back logic.

    The thread pool consists of four threads that are used to delegate operations that are too large for the event loop to handle. I/O operations, such as opening and closing connections and setting timeouts, are examples. 

    When a task is completed by the thread pool, a callback function is invoked, which handles the error (if any) or performs some other operation. The event queue receives this callback function. The event goes through the event queue and delivers the callback to the call stack when the call stack is empty. 

    nodejs event loop diagram 


    To get the detailed knowledge of event loops and other concepts of node js you can opt for node js best course  online of knowledgehut. 

    The Node.js Event Loop Explained

    JavaScript is single thread. It just has one call stack and one memory heap. It's synchronous, which means the code runs sequentially... 

    console.log(1) 

    console.log(2) 

    console.log(3) 

    //logs 

    This makes reasonable, yet it might be inconvenient if anything takes a long time to complete... 

    let data = fs.readFileSync('MyFile.csv')  

    processData(data) 

    someOtherFunction() 

    Depending on the file's size, reading it may take some time. Because javaScript is asynchronous, we must wait for readFileSync to finish before proceeding. 

    Callbacks to the Rescue

    It can take a long time to wait for blocking operations (talking to the file system, sending HTTP requests, reading from a database). The rest of our code shouldn't have to wait for these synchronous activities to finish. 

    We can create synchronous (blocking) operations asynchronous by using callbacks (non-blocking). 

    fs.readFile('MyFile.csv', (err, data) => { 
    if(err) throw err 
    processData(data) 
    }) 

    someOtherFunction() 

    The second argument in fs.readFile() is a callback function, as you can see. When the file read is finished and the data is available, this function is called. An exception will be thrown if there are any errors reading the file. 

    This is an asynchronous technique for dealing with blocking I/O. Without waiting for fs.readFile() to complete, the script can continue on to someOtherFunction(). Only after the data is provided via the callback function does the processData() method execute. 

    Callbacks and the Node.JS Eventloop

    With Node, callbacks are nothing new. They reflect a long-established design pattern in classical JavaScript. 

    Callbacks are a simple way of saying "hey, when this is finished, do this." To register events in the event loop, Node simply uses callbacks on specific functions. 

    Phases of Event Loop

    The Event Loop consists of the six phases listed below, which are repeated as long as the application's code has to be executed: 

    • Timers 
    • I/O Callbacks 
    • Waiting / Preparation 
    • I/O Polling 
    • setImmediate() callbacks 
    • Close events 

    Phases of Event Loop

    Timers

    The core timers module in Node.js provides timers, or functions that perform callbacks after a given amount of time. setTimeout() and setInterval() are two global functions provided by this module (). These let you to define code that will run once a certain amount of time has passed. 

    The Event Loop executes the timers phase directly. The Event Loop changes its own time at the start of this phase. The timers are then checked in a queue or pool. All timers that are currently set are in this queue. The Event Loop compares the timer with the least wait time to the current time of the Event Loop. The timer's callback is scheduled to be triggered once the call stack is empty if the wait time has expired. 

    There are two types of timers in Node.js: setTimeout() and setInterval() (). The main difference is that setInterval() has a repeat flag, which returns the timer to the queue once it has completed its execution. 

    I/O Callbacks

    I/O refers to reading/writing files or network operations in Node.js. Network operations allow you to bring in external data or send data from your program to another location. We'll use the file system as an example, although you could instead use network activities to examine these instances. 

    When your program is waiting for a file to be read, it is not required to wait until the system returns with the file's content. It can keep running code and asynchronously receive the file's content when it's ready. 

    Non-blocking, I/O interfaces enable us to do this. The asynchronous I/O request is queued, and the main call stack can then continue to function normally. The I/O callbacks of completed or errored out I/O operations are processed in the second phase of the Event Loop. 

    Idle, Prepare

    The Event Loop executes internal activities on any callbacks during this phase. Technically, there is no way to change the length or nature of this phase. During this phase, there is no mechanism in place to guarantee code execution. It is mostly used for gathering data and preparing what actions should be taken on the next tick of the Event Loop. 

    Poll

    This is the stage wherein the launch all of the JavaScript code we've created from top to bottom. Relying on the code, it could run immediately or add anything to the list to be handled on a subsequent iteration of the Event Loop. 

    The Event Loop manages the I/O workload during this phase, calling the functions in the queue until the queue is empty, and calculates how long it should wait before going on to the next phase. In this phase, all callbacks are synchronously called in the order in which they were added to the queue, from oldest to newest. 

    If any setImmediate() timers are scheduled during the current tick, Node.js will skip this phase and proceed to the setImmediate() phase.

    If there are no timers or functions in the queue, the program will wait for callbacks to be added to the queue and then execute them until the internal setTimeout() that was set at the start of this phase expires. It continues on to the next step after that. The duration of this timeout is likewise determined by the status of the application. 

    Check

    The callbacks scheduled by setImmediate() are handled in this phase, and they will be executed once the Poll phase is idle. 

    SetImmediate() in Node.js is a specific timer that executes callbacks during this period. When the poll phase is idle, this phase starts. SetImmediate() will always be executed before other timers if it is scheduled within the I/O cycle, regardless of how many timers are present. 

    Close Callback

    If a socket or handle is abruptly closed, the 'close' event is emitted, this phase handles callbacks. 

    All closing event callbacks are executed in this phase. A closing event of a web socket callback, for example, or process.exit() is called. This is the point at which the Event Loop has completed one cycle and is ready to go on to the next. It is primarily used to clear the application's state. 

    Callbacks for timers whose wait time has expired are executed in sequence from smallest to longest wait time. I/O callbacks are then performed, followed by internal processing. The main code enters the picture after that, and I/O poll queue callbacks are executed. The setImmediate() and close event callbacks are then called. The timers begin the following tick. This loop will continue as long as there is code to execute. 

    Monitoring the Event Loop

    We can see that the event loop controls everything that happens in a Node application. This means that if we can extract metrics from it, they should provide us with useful information about an application's general health and performance. 

    Because there is no API for retrieving runtime metrics from the event loop, each monitoring tool must offer its own metrics. Let's have a look at what we come up with. 

    • Tick Frequency 

    The number of ticks per time. 

    • Tick Duration 

    The duration of one tick. 

    Because our agent operates as a native module, adding probes to supply us with this information was extremely simple. 

    Tuning the Event Loop

    Of course, metrics are useless unless you know how to use them to generate potential solutions to problems. Here are some suggestions for what to do if the event loop appears to be running out of steam. 

    • Utilize all CPUs 

    A single thread runs a Node.js application. This indicates that the load isn't distributed evenly across all cores on multicore devices. It's simple to spawn a child process per CPU using the cluster module that comes with Node. Each child process has its event loop, and the master process ground into fine the load across all children. 

    • Tune the Thread Pool 

    Node js libuv will make a four-thread pool. By changing the environment variable UV_THREADPOOL_SIZE, you can change the pool's default size. 

    While this can address load concerns in I/O-bound apps, I wouldn't recommend doing too much stress testing because a larger thread pool can still exhaust memory or CPU. 

    • Offload the work to Services 

    Offloading work to services or even utilising another language that better suits a certain task could be a realistic choice if Node.js spends too much time with CPU-intensive tasks. 

    Unlock the Power of Python! Join our online course for Python and earn a certificate. Learn the language that's revolutionizing the tech world. Enroll now!

    Conclusion

    Understanding the event loop is an important component of learning Node.js, whether you're looking to learn more about the technology, increase its performance, or just find a fresh and intriguing reason to learn something new. 

    Timers, I/O callbacks, preparation / idle phase, I/O polling, setImmediate() callbacks execution, and close events callbacks are the six primary phases of the Event Loop. When a phase is finished, the application advances to the next tick, and all phases are replayed, beginning with timers, until there is nothing further to process. 

    If you are thinking of getting a job a a NodeJS developer or want a hike in your job then you must check knowledgeHut’s node js best course. It includes 24 hours of live instructor led training. 

    Frequently Asked Questions (FAQs)

    1How does event loop work?

    The Event Loop's sole purpose is to keep track of the Call Stack and Callback Queue. The Event Loop will take the first event from the queue and push it to the Call Stack if the Call Stack is empty, essentially running it. 

    2Why is node js called event driven?

    Event-driven programming is used in Node. js. It means that when Node begins its server, it simply sets up variables, defines functions, and then waits for something to happen. It's one of the reasons Node exists. 

    3What is async and await in node JS?

    Async functions are defined by the async keyword in their declaration and are available natively in Node. Even if you don't expressly tell them to, they always return a promise. Furthermore, the await keyword is currently only available within async functions and cannot be used in the global scope. 

    4How event loop is non-blocking?

    Even though JavaScript is single-threaded, the event loop allows Node. js to conduct non-blocking I/O operations. The loop picks a task from the code and executes it on the same thread as the JavaScript code. 

    5How do you create an event loop?

    Before pushing callbacks from the Task Queue to the Call Stack, the event loop waits for the Call Stack to be cleared. The event loop is triggered once the Stack is cleared, and it examines the Task Queue for available callbacks. 

    6Is event loop single thread?

    Only a single thread is used in Event Loop. It is the primary component of the Node JS Platform Processing Model. Any Client Request filed in the Event Queue is also checked by Loop. 

    Profile

    Abhresh Sugandhi

    Author

    Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon