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.

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay