DEV Community

Ugizwenayo-Divine
Ugizwenayo-Divine

Posted on

Event loop in nodejs

Nodejs is a single threaded application. That means it executes instructions or all requests with a single thread.
In node js all request or operations are served by one thread that means there is one operation being executed at time.

So event loop is what allow nodejs to perform non-blocking operations.
Given it uses one thread in serving many requests, the request does not have to wait the completion of the first request, that's where event loop come into existence and allow one request to release the thread while waiting for I/O operations.

When there is a request, single thread is used to serve it but does not have to wait its completion once there are some executions being done for that request to complete like waiting for I/O inputs ,the single thread is serving another request.
Once the first request is done with other executions(I/O input are available) there is this event queue where messages notifying that data are now available go. Then the single thread will return to serve the first request.

This event loop allows non-blocking operations by offloading operations to the
kernel whenever possible.The event loop manages events(requests) by taking the first request on list and send it to be served or handled by the only one thread, also if the request is not using the thread that's when it offload event to the thread.

references:
https://nodejs.org/uk/docs/guides/event-loop-timers-and-nexttick/
https://nodejs.dev/the-nodejs-event-loop
https://blog.risingstack.com/node-js-at-scale-understanding-node-js-event-loop/

Top comments (0)