What is the difference between the event loop in JavaScript and async non-blocking I/O in Node.js?
Asked Answered
T

3

17

In this answer to the question -

What is non-blocking or asynchronous I/O in Node.js?

the description sounds no different from the event loop in vanilla js. Is there a difference between the two? If not, is the Event loop simply re-branded as "Asynchronous non-blocking I/O" to sell Node.js over other options more easily?

Tryparsamide answered 2/12, 2021 at 14:10 Comment(2)
Yes! "green threads" is a relatively new concept which was brought to servers through NodeJS (which was uncommon in Java, C# etc. back then). It's bringing the event loop concept from JavaScript to server runtimes.Neuritis
Hmm...I don't think that event loop is simply re-branded as 'Async non-blocking I/O'. The purpose of the event loop is the same in both cases but the call-backs queue is Web APIs for the browser (Vanilla js) and C/C++ APIs i.e, libuv library - a focus on asynchronous I/O for Node.js. So I believe libuv library is key here... I picked the concept of understanding from Philip Roberts' video - youtube.com/watch?v=8aGhZQkoFbQ.Roosevelt
B
12

The event loop is the mechanism. Asynchronous I/O is the goal.

Asynchronous I/O is a style of programming in which I/O calls do not wait for the operation to complete before returning, but merely arrange for the caller to be notified when that happens, and for the result to be returned somewhere. In JavaScript, the notification is usually performed by invoking a callback or resolving a promise. As far as the programmer is concerned, it doesn’t matter how this happens: it just does. I request the operation, and when it’s done, I get notified about it.

An event loop is how this is usually achieved. The thing is, in most JavaScript implementations, there is literally a loop somewhere that ultimately boils down to:

while (poll_event(&ev)) {
    dispatch_event(&ev);
}

Performing an asynchronous operation is then done by arranging for the completion of the operation to be received as an event by that loop, and having it dispatch to a callback of the caller’s choice.

There are ways to achieve asynchronous programming not based on an event loop, for example using threads and condition variables. But historical reasons make this programming style quite difficult to realise in JavaScript. So in practice, the predominant implementation of asynchrony in JavaScript is based on dispatching callbacks from a global event loop.

Put another way, ‘the event loop’ describes what the host does, while ‘asynchronous I/O’ describes what the programmer does.

From a non-programmer’s bird’s eye view this may seem like splitting hairs, but the distinction can be occasionally important.

Blackandwhite answered 10/12, 2021 at 8:44 Comment(0)
S
8

There are 2 different Event Loops:

  1. Browser Event Loop
  2. NodeJS Event Loop

Browser Event Loop

The Event Loop is a process that runs continually, executing any task queued. It has multiple task sources which guarantees execution order within that source, but the Browser gets to pick which source to take a task from on each turn of the loop. This allows Browser to give preference to performance sensitive tasks such as user-input.

There are a few different steps that Browser Event Loop checks continuously:

  • Task Queue - There can be multiple task queues. Browser can execute queues in any order they like. Tasks in the same queue must be executed in the order they arrived, first in - first out. Tasks execute in order, and the Browser may render between tasks. Task from the same source must go in the same queue. The important thing is that task is going to run from start to finish. After each task, Event Loop will go to Microtask Queue and do all tasks from there.

  • Microtasks Queue - The microtask queue is processed at the end of each task. Any additional microtasks queued during during microtasks are added to the end of the queue and are also processed.

  • Animation Callback Queue - The animation callback queue is processed before pixels repaint. All animation tasks from the queue will be processed, but any additional animation tasks queued during animation tasks will be scheduled for the next frame.

  • Rendering Pipeline - In this step, rendering will happen. The Browser gets to decide when to do this and it tried to be as efficient as possible. The rendering steps only happen if there is something actually worth updating. The majority of screens update at a set frequency, in most cases 60 times a second (60Hz). So, if we would change page style 1000 times a second, rendering steps would not get processed 1000 times a second, but instead it would synchronize itself with the display and only render up to a frequency display is capable of.

Important thing to mention are Web APIs, that are effectively threads. So, for example setTimeout() is an API provided to us by Browser. When you call setTimeout() Web API would take over and process it, and it will return the result to the main thread as a new task in a task queue.

The best video I found that describes how Event Loops works is this one. It helped me a lot when I was investigating how Event Loop works. Another great videos are this one and this one. You should definitely check all of them.

NodeJS Event Loop

NodeJS Event Loop allows NodeJS to perform non-blocking operations by offloading operation to the system kernel whenever possible. Most modern kernels are multi-threaded and they can perform multiple operations in the background. When one of these operations completes, the kernel tells NodeJS.

Library that provides the Event Loop to NodeJS is called Libuv. It will by default create something called Thread Pool with 4 threads to offload asynchronous work to. If you want, you can also change the number of threads in the Thread Pool.

NodeJS Event Loop goes through different phases:

  • timers - this phase executes callbacks scheduled by setTimeout() and setInterval().

  • pending callbacks - executes I/O callbacks deferred to the next loop iteration.

  • idle, prepare - only used internally.

  • poll - retrieve new I/O events; execute I/O related callbacks (almost all with the exception of close callbacks, the ones scheduled by timers, and setImmediate()) Node will block here when appropriate.

  • check - setImmediate() callbacks are invoked here.

  • close callbacks - some close callbacks, e.g. socket.on('close', ...).

Between each run of the event loop, Node.js checks if it is waiting for any asynchronous I/O or timers and shuts down cleanly if there are not any.

In Browser, we had Web APIs. In NodeJS, we have C++ APIs with the same rule.

I found this video to be useful if you want to check for more information.

Scission answered 10/12, 2021 at 6:41 Comment(0)
F
1
  • For years, JavaScript has been limited to client-side applications such as interactive web applications that run on the browser. Using NodeJS, JavaScript can be used to develop server-side applications as well. Though it’s the same programming language which is used in both use cases, client-side and server-side have different requirements.

  • Event Loop” is a generic programming pattern and JavaScript/NodeJS
    event loops are no different. The event loop continuously watches for any queued event handlers and will process them accordingly.

  • The “Events”, in a browser’s context, are user interactions on web
    pages (e.g, clicks, mouse movements, keyboard events etc.), but in
    Node’s context, events are asynchronous server-side operations (e.g, File I/O access, Network I/O etc.)

Frecklefaced answered 14/12, 2021 at 15:51 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Accentuate

© 2022 - 2024 — McMap. All rights reserved.