DEV Community

Cover image for Difference between the Event Loop in Browser and Node Js?
Jasmin Virdi
Jasmin Virdi

Posted on • Edited on

Difference between the Event Loop in Browser and Node Js?

Every JS developer must have heard of the term Event Loop. Both JS and Node Js is based on the principle of event loop which has similarities and dissimilarities to some extent. Let's discuss the event loop in brief and find the difference between them. 📖

Event Loop in Browser

Browser Event Loop
Let's cover each section in brief here:

  1. Heap - It stores all the object reference and variables that we define in our function.

  2. Call Stack - All the function that we use in our code is stacked here in LIFO manner such that the last function is at the top and first function is at the bottom.

  3. Web API's - These API's are provided by browser which provides additional functionality over V8 engine. The functions which uses these API's are pushed to this container which on completion of the response of Web API is popped out of this container.

  4. Queues - The queues are used to compute the asynchronous code response such that it doesn't block engine to execute further.

    • Macro Task Queue - This queue executes async functions like DOM events, Ajax calls and setTimeout and has lower priority than Job queue.
    • Micro Task Queue - This queue executes async functions which uses promises and has higher precedence over Message Queue.

The event loop checks the Call Stack, if the stack is empty it pushes the functions in the Queues to Call Stack and runs it. Functions already present are given higher priority and runs first in comparison to functions in message queue.

Event Loop in Node Js

Node Js Event Loop

The Node Server consist of following parts:

  1. Event Queue - On completion of the Thread Pool a callback function is issued and sent to the event queue. When call stack is empty the event goes through the event queue and sends callback to the call stack.

  2. Thread Pool - The thread pool is composed of 4 threads which delegates operations that are too heavy for the event loop. I/O operations, Opening and closing connections, setTimeouts are the example of such operations.

  3. Event loop in Node Js has different phases which has FIFO queue of callbacks to execute. When event loop enters a given phase it operates callbacks in that phase queue until the queue has been exhausted and maximum number of callbacks has executed and then moves to next phase.

Node Js Event Loop Phases

The Event Loop is an endless loop which waits for the tasks, executes them and then sleeps until it receives more tasks. The event loop executes tasks from queue only when stack is empty. It processes the oldest task first and allows us to use callbacks and promises.

Difference between both the event loops?

  1. First difference is node uses a thread pool to manage disk I/O. It executes the I/O and other timer API's asynchronously.

  2. Browser does not have setImmediate() function. This function execute once the I/O operation is done, if particular code is inside this it will be executed first. Whereas in setTimeout() callback function is executed after given minimum threshold value in milliseconds.

  3. Node Js event loop has multiple phases and each phase handle specific type of tasks whereas browser has micro task and macro task queue within which all the tasks are processed in order they were placed into the queue.

  4. In a browser when you open a page in a tab, you actually create a process in which there can be multiple threads, such as JS engine, page rendering, HTTP request threads and many more. Whereas in Node JS when you initiate a Client Request which performs Blocking I/O operations, event loop picks up a thread and assign the client request to that thread as Event loop is single threaded.

These are some major differences between the event loops for Node JS and Browser. Let me know if I missed something 😅

Happy Learning! 👩🏻‍💻

Latest comments (25)

Collapse
 
cygnus profile image
Cygnus X1

दीदी do you mind if I use these diagrams in an internal training session?

Collapse
 
tannath profile image
tannath

Why (when) then libuv will be brought to Browser?
libuv.org/

Collapse
 
vishalbhandare profile image
vishal bhandare

Can we say this?
Event Queue in Node Js is same as micro task and macro task queue from browser

Collapse
 
kritikag1997 profile image
Kritika Gaur

This is very important point which we all should know about the event loop in Browser or in Node js

While Nodejs uses the Google V8 as its runtime, it does not use V8 to implement the event loop.

Nodejs uses the Libuv library (written in C) to implement the event loop.

Collapse
 
shinthant profile image
Shin Thant

Thanks for the amazing article.
Just one thing. I think the

'Incoming connections, data, etc...'
is for poll phase.

Thank you!

Collapse
 
bokomoko profile image
João Eurico "Bokomoko" Lima

Amazing explanations.

Congrats and thanks for sharing knowledge.

Collapse
 
khaledinges profile image
Khaledinges

"Whereas in Node JS you initiate a request, you actually create a thread that may be destroyed when the request is completed"

It is incomplete as information. This is actually correct for the first request on the server, when you will have other requests or simultaneous requests, Node.js will still have one thread async processing.

Other languages like rust, java, .net have those type of concepts, I mean multi-threading approach.

Collapse
 
henningsummer profile image
Henning Summer

Thanks!

Collapse
 
iostreamer profile image
Rahul Ramteke

Node doesn't always use a thread pool. At its core it relies on operating system's ability to intimate it about certain events, for example kequeue, epoll etc.

The burden of actually executing the async operation and notifying node lies with OS. But for cases where that's not possible, it falls back to the threadpool. For example dns resolution is handled by thread pool, but file and socket operations are mostly OS.

Collapse
 
paiatpeace profile image
Ameya Pai

How do you know this? Did you read this somewhere or did you come across some system tool which helped you to see this? Please let us know...

Collapse
 
iostreamer profile image
Rahul Ramteke
Collapse
 
projektorius96 profile image
LG • Edited

Instead of forking (crude-cloning) processes into splitted (distinct) context for each child process,
we instead employ workers (CPU heavy computations e.g. for DNS lookup) within single-threaded-context (thread pool) . I see workers (a.k.a. threads) as some sort of virtualization (optimization) within same boundaries of memory (RAM) at time . This image helped me a lot to comprehend what I stated in my comment above ; I'll be honest I may be mistaken , always welcome to give alternative argument for that .

Collapse
 
iostreamer profile image
Rahul Ramteke

That's a nice article! Although, just to re-iterate, I was talking about the threadpool which libuv maintains.
A very brief explaination :
As I mentioned, at its core, node expects the OS to do the heavylifting. And different Operating Systems have different mechanism of doing that, hence node folks built an abstraction library called libuv. This library abstracts event loop and the OS interactions(fun fact, you can use this lib stand alone).
Now, let's say there's an operation which node wants to do differently, or there's something which OS can't handle or doesn't support. To manage such scenarios libuv has its own threadpool, and this threadpool(default size 4) simulates the async behavior which node expects from OS.

Collapse
 
jasmin profile image
Jasmin Virdi

Thanks for adding up☺️

Collapse
 
_sathikbasha profile image
Sathik

Good work

Collapse
 
jasmin profile image
Jasmin Virdi

Thank you!☺️

Some comments may only be visible to logged-in visitors. Sign in to view all comments.