A Beginner’s Guide To Eventloops in Node.Js https://www.fibonalabs.com /
A presentation at A Beginner’s Guide to Eventloops in Node.js in December 2023 in by Fibonalabs
A Beginner’s Guide To Eventloops in Node.Js https://www.fibonalabs.com /
Node.js turned 12 on May 27th this year, so what’s a better time than now to brush up our knowledge about the most important feature of Node.js: Event Loops! Here’s an index of what you can expect from this blog: > What is Node.js? > What is The Event Loop? > Event Loop Explained > Phases Overview > Conclusion
Let’s get started! > What is Node.js? Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, nonblocking I/O model that makes it lightweight and efficient, perfect for dataintensive real-time applications that run across distributed devices.
What is The Event Loop? This event loop is something that allows Node.js to perform non-blocking I/O operations which we read about earlier. Event loops allow this despite the fact that JavaScript is single-threaded, by offloading operations to the system kernel whenever possible.
Since most modern operating systems/kernels are multi-threaded, they can handle multiple operations executing in the background. When one of these operations completes, the kernel tells Node.js so that the appropriate callback may be added to the poll queue to eventually be executed. > Event Loop Explained The Node.js Event Loop has the following six phases, which are repeated for as long as the application still has code that needs to be executed: 1. Timers 2. Pending Callbacks 3. Idle, Prepare 4. Poll 5. Check
Phases Overview 1. Timers: A timer specifies the threshold after which a provided callback may be executed rather than the exact time a person wants it to be executed. This phase executes callbacks scheduled by setTimeout() and setInterval(). setTimeout(,0) executes after all the current functions in the present queue get executed. SetImmediate() is similar but it doesn’t use a queue of functions. It checks the queue of I/O event handlers. If all I/O events in the current snapshot are processed, it executes the callback.
THANK YOU