DEV Community

loading...
Cover image for Event Loop

Event Loop

Anguram Shanmugam
Be Good On Doing
・5 min read

Disclaimer: This article is all about event-loop. It may have soo many dependency articles or too little. But It will confuse you like christopher nolan movies. So, Save your brains✌

Let's Begin 🚀
Let's Begin

EventLoop

In a nutshell it's a loop. But differ from other loops i.e., from movies or traditional loop(for, while). Because, you can't write this eventloop. In nature it's declarative. I know you won't get nothing with the definition above 🤷‍♂️.

It's Okay let's go for an analogy tour. Let's use flash from DC Comics. If anyone not familiar with "flash". He's speedster, nerd, moron, who got superpower from lighting. Not only that it makes him run like thunder.
If you think that you don't get it. Just see the intro of any episode. Same blah blah blah for every episodes😒😒😒
The Flash Series | Intro
Troll Flash

There's an episode in flash which very opt for this article. But I don't wanna stack you with these sci-fi stuffs. So, Imagine flash running on a Athlete track with his lighting speed⚡
Athlete Track

According to flash he see stuffs too slow which is completely opposite for us. So, I let's make him to do some stuffs.
For example: I want him to capture photo of 734th seat in the stadium and also I want him to change lane for every time he take photo of 734th seat in the stadium.
So much math

I don't want you to calculate. Just letting you know his capability⚡
This is event-loop. It runs on it's track by doing the tasks/process in the main thread.
unbelievable

Main Thread?

Don't worry this is not gist article. Trust me!

In nature JavaScript is single-threaded i.e. it runs in single procress of CPU's bunch of processes. Process are called thread. Because it's good to have a convention which stick tight to the processor POV. Each core are compatible for certain limit of threads and virtualization, etc,. that's processor side which we don't really need here.

The thing is simple. The app you're running which is built in javascript runs only in one thread. That thread is known as main thread and that's where event-loop a.k.a flash now runs😅 just joking!. But here's the nolan twist for you 🤗. Well it's not totally true.
deal with it

Well the main purpose of the eventloop is to stick with main thread. So, whenever you pass a task which need more time to process. Then the eventloop will mark it and sends it to the engine i.e. JavaScript Engine. The engine runs the process and let the eventloop know when it's done. Then eventloop get the finished process from engine and do it's stuffs.

If you still struggling to wrap your head around?
Okay, I told you above, That there's an episode in flash which is very opt right!
watch the below youtube video.

See! The main thread a.k.a is not protaganist anyway😂.
just kidding. he is. Then why do we need a thread like 'savitar' anyways right?

Well It turns out. We need it. because nowadays I don't wait to see the above video loading for even a second. I need that blazing fast performance✨ out of everything. because CPU's gettings shrink to 2nm & even smaller (Anyway it don't know what is corona! I need to declare that 🤷‍♀️)
moron

So, Threads will take care of that heavy lifting. Event-loop will let the Engine know about the process and engine creates or use another thread(like Poor Savitar😅) then join it to the main thread.

But Actually how this works in JavaScript?

JavaScript has three concepts that we need to know first.

  • Promises
  • callback
  • async await

Here's an free token to get out this article. You can either watch the below youtube videos to getting professional level knowledge(see it in order) or if you're good with me then trust I'll save you 🤗

Back to article

If you're reading still. Thanks mate for trusting me🤧
Thanks

Promises

It's nothing but the promise your girlfriend/boyfriend made to you😂. Either It'll be fulfilled or rejected a.k.a fake promise🤣.

Yeah, It's true. let me show you.

const myLovePromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});

myLovePromise
.then(handleResolvedA, handleRejectedA)
.then(handleResolvedB, handleRejectedB)
.then(handleResolvedC, handleRejectedC)
.catch(err => { console.log(err) });
Enter fullscreen mode Exit fullscreen mode

Every promise will have two parameters. Using this we can attach many function/operations depending on a single promise. This process is called promise-chaining.

Simple right

Callback

It's the cool feature I've ever seen. A Callback function is just function. But passed an argument. See 😃 it's freakin awesome right!

// normal function
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

// function which accepts a function as parameter: myCallback
function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}

// Passing function as a parameter
myCalculator(5, 5, myDisplayer);
Enter fullscreen mode Exit fullscreen mode

If you need a simple and sweet example. Take setTimeout Function. All need to do is to pass your operations in as function with the delay.

Async Await

This is an syntatic sugar for promises. After using the above method for some time. You'll realise that you are just pouring code in a single block. Instead of adding more readability to the code. That's where async await come in to picture.

I tried

Finally

As it turns out event-loop handle these three concepts efficiently by catagorize them as Microtasks and Macrotasks. Each are treated in each way. For an elaborated explanation use MDN Docs.

So, Eventloop in JavaScript is crucial when it comes to task management. In server-side with the help of NodeJS, You can play with the eventloop to get a good picture out of it.

Hope I confused you most enough with my explanation.
IDC

Some developers openly stated in many videos, articles that JavaScript confusable and non-sensicle language.

But If you ask me! 🤷‍♀️
thats what she said

Com'on mate, It's a friendly programming language.

Discussion (0)