Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 535
Flame of udun Avatar asked Dec 02 '21 14:12

Flame of udun


People also ask

What is the difference between asynchronous and non-blocking NodeJS?

Non-Blocking: It refers to the program that does not block the execution of further operations. Non-Blocking methods are executed asynchronously. Asynchronously means that the program may not necessarily execute line by line.

Is JavaScript blocking or non-blocking?

JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language with lots of flexibility.

What is the event loop in NodeJS?

The event loop is what allows Node. js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible. Since most modern kernels are multi-threaded, they can handle multiple operations executing in the background.

What is the difference between blocking synchronous and non-blocking asynchronous code?

Blocking and synchronous mean the same thing: you call the API, it hangs up the thread until it has some kind of answer and returns it to you. Non-blocking means that if an answer can't be returned rapidly, the API returns immediately with an error and does nothing else.

What is event loop and asynchronous non blocking in Node JS?

In the previous article, we talked about Node js network programming. Here we will take it further and talk about Event loop and asynchronous non blocking in node js. Node.js is single threaded. It supports concurrency through paradigms of event and callbacks. Since it is single threaded, most APIs provided by Node.js core are asynchronous.

What is the difference between asynchronous and nonblocking I/O in JavaScript?

There are few ways of communication that a nonblocking I/O has completed. The callback function is to be called when the operation is completed. Nonblocking call uses the help of javascript which provides a callback function. You can point out the differences with these definitions of asynchronous and nonblocking.

What is an event loop in JavaScript?

This loop is famously known as the Event Loop. When a Browser API occurs, park the callback functions in a queue. Keep executing code as usual in the stack. The event loop checks if there is a callback function in the queue. If so, pull the callback function from the queue to the stack and execute.

What is an event in Node JS?

In Node.js events are associated with operations in Event Loop. For example, a TCP network server emits a _connect_ event every time a new client connects, or a stream can emit a _data_ event every time a new chunk of data is available to read. These objects in Node.js are called _event emitters_.


Video Answer


3 Answers

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.

like image 67
user3840170 Avatar answered Oct 18 '22 22:10

user3840170


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.

like image 20
NeNaD Avatar answered Oct 18 '22 23:10

NeNaD


  • 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.)

like image 1
A K Avatar answered Oct 18 '22 21:10

A K