Month End Sale: Get Extra 10% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now

Node.js Event Loop

Level : Beginner
Mentor: Shailendra Chauhan
Duration : 00:02:00

Node.js Event Loop

The Node.js execution architecture is built on the JavaScript Event loop, which is single-threaded and uses a JavaScript callback mechanism. The event loop allows Node.js to manage concurrent requests.

Why is the Event Loop important?

Most operating systems are multi-threaded, allowing them to manage numerous operations in the background. When one of these operations is complete, the kernel notifies Node.js, and the callback assigned to that operation is added to the event queue, where it will eventually be executed. 

Event Loop Features

  • The event loop is an infinite loop that handles jobs and sleeps until more arrive.
  • When the call stack is empty, it executes jobs from the event queue.
  • Allows the use of callbacks and promises.
  • Tasks are carried out in order of descending age.

Working of Event Loop

  • Node.js initializes the event loop, processes the input script, and sets timers.
  • Uses libuv for asynchronous tasks and controls the libuv thread pool.
  • The thread pool delegates heavy activities such as I/O operations and setTimeouts.
  • Once the task is completed, the callback function is added to the event queue.
  • When the call stack is empty, callbacks are executed from the event queue.

Event Loop Phases

  • Timers: This phase handles timers that were set with setTimeout() and setInterval().
  • Pending Callbacks: This phase handles any callbacks added to the message queue by asynchronous functions. 
  • Idle and Prepare: "idle.ignore" is not a regular event loop phase in Node.js; it is used internally. During the "idle" phase, the event loop has no tasks but can manage background ones. "idle. ignore" bypasses the idle phase, blocking background tasks during that period.
  • Poll: This phase checks for new I/O events and processes any that are identified.
  • Check: This phase handles any setImmediate() callbacks introduced to the message queue.
  • Close Callbacks: The "close" phase manages callbacks introduced to the message queue by socket close events. This phase involves the execution of socket closure-related code.
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this