DEV Community

Sunbeom Kweon (Ben)
Sunbeom Kweon (Ben)

Posted on

[Advanced Node JS] 1 - Event Loop

Event Loop is one of the most important concepts in JavaScript(Browser) & Node JS.

Event Loop is also the biggest difference between other classic programming languages like C/C++ or Java.

Node JS vs Browser

Browser and Node JS both have their own Event Loop. Node JS Event Loop is a little bit complex and has more phases, but both shares the same concept. I am going to introduce the Browser's Event Loop.

Difference Between The Event Loop in Browser and Node JS

Synchronous Call vs Asynchronous Call

Synchronous calls goes to Stack, just like other programming languages. They get executed until the stack is empty.

But asynchronous calls goes to Queue (Event Loop). This is how Event Loop looks like in a simple code:

while (queue.waitForMessage()) {
  queue.processNextMessage();
}
Enter fullscreen mode Exit fullscreen mode

The message polling occurs when the stack is empty. So all the synchronous calls will be processed first. Since synchronous functions are pushed to the stack first, all queued functions(messages) need to wait to be processed.


// Synchronous Call
console.log("1: Pushed to stack");

// Asynchronous Call
setTimeout(()=>{
    console.log("1: Pushed to queue");
}, 1000);

// Synchronous Call
console.log("2: Pushed to stack");

// > Output: 
// 1: Pushed to stack
// 2: Pushed to stack
// 1: Pushed to queue
Enter fullscreen mode Exit fullscreen mode

Image description

The processing of functions continues until the stack is once again empty. Then, the event loop will process the next message in the queue (if there is one). Each message in the queue contains a function. Therefore, polling a new message from queue will push a function on the top of the Stack.

We would like to use the queue(Event Loop) when the function's workload is heavy. Normally on web browsers, when we call any Web APIs such as setTimeout, eventListener those function calls will be queued.

Top comments (0)