What is the different between JavaScript Event loop and Node.js Event loop?
The Nodejs event loop implementation differs from the browser-based event loop one.
This is a huge point of confusion in the Nodejs community.
While Nodejs uses the Google V8 as it's runtime, it does not use V8 to implement the event loop.
Nodejs uses the Libuv library (written in C) to implement the event loop.
The digram you have above, which works for the JS event loop, is not the same for the Nodejs event loop.
There are three references you should study in order to fully understand the Nodejs event loop:
- https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/
- http://docs.libuv.org/en/v1.x/design.html
- https://www.youtube.com/watch?v=sGTRmPiXD4Y
Both chrome
and node
has their own event-loop
.
The Event Loop in the Browser or Node is not part of V8. The Event Loop Is Part of a different application/dependency/library which is provided by the Browser or Node
They do not use V8
's event loop.
V8 does implement an event loop, it is there.
However it is meant to be overridden or replaced, which is something both Chrome and NodeJS happen to do.
Browser (Chrome)
V8 just executes your JavaScript (If and else statements, for statements, functions, arithmetic operations e.t.c) and then hands over operations to Libevent.
In the Browser(e.g Chrome) apart from JavaScript Engine V8 (Chrome uses V8), the browser also contains different applications/dependencies/libraries which can do a variety of things like sending HTTP requests, listen to DOM events, delay execution using setTimeout or setInterval, caching, database storage, and much more.
Therefore the Browser (e.g Chrome) uses the dependency Libevent to implement the Event Loop.
Node.js
V8 just executes your JavaScript (If and else statements, for statements, functions, arithmetic operations e.t.c) and then hands over operations to Libuv. JavaScript by default does not have support for networking and file system operations. Libuv works with V8 so that V8 will run the JavaScript and Libuv will handle I/O tasks.
In Node.js apart from JavaScript Engine V8, Node also contains different applications/dependencies/libraries which can do a variety of things such as Networking, File System Operations, Listen To System Events, delay execution using setTimeout, setInterval, setImmediate, process.nextTick, and much more.
Therefore Node.js uses the dependency Libuv to implement the Event Loop.
Node's event loop sit idle if there is no tasks in the callback queue (phases), but Chrome's event loop keeps running
Chrom's event loop is like merry-go-round while Node's event loop is like Roller coaster
There are other difference too, you can look here.