What the heck is Event Loop in JavaScript
Mike runs to me and says "Excuse me sir, please I have been learning JavaScript for a while now, but this event Loop concept is a mystery to me, can explain to me better?"
Me:
Hahhhahha, I am not surprised, I still remember when learning JavaScript, Event Loop was a headache to me too. Until I stumbled on Philip Roberts' Video, where he explained event Loop visually.
Mike: Sir, what the heck is event Loop?
Me:
JavaScript is a single threaded programming language, what this means is that JavaScript handles tasks once a time on the browser, other programming languages like Java etc have about 200 or more threads to handle tasks concurrently. But JavaScript handles one task at time, when done it moves to the next task.
What event Loop does is manage the activities, assigning tasks between the stack, event queue and your console(rendering).
Mike: Stack, event queue, and console?
Me: Yes, but we would not dive into those now.
Mike: How does it work?
Me: I have initially told you that JavaScript does one task at a time, yes, but in the browser there are other things like web API, HTTPS etc, provided by the browser, Javascript extensively use the web API.
Let assume we pass a callback function and a delay of 5 secs to the setTimeout call.
Now setTimeout is an API provided to us by the browser, it's extra stuff we get while running the JavaScript run time. The browser kicks off a timer for you. It's going to handle the count down for you, that means our setTimeout call, itself is now complete, so we can pop off the stack.
Now we've got this timer in the web API, which five seconds later is going to complete. Now the web API can't just start modifying your code, it can't chuck stuff onto the stack when it's ready.
If it did it would appear randomly in the middle of your code so this is where the task queue or callback queue kicks in.
The web APIs push the callback onto the task queue when it's done. Finally we get to the event loop, It has one very simple job. The event loop's job is to look at the stack and look at the task queue. If the stack is empty it takes the first thing on the queue and pushes it on to the stack which effectively runs it.
So you can see that now the stack is clear, there's a callback on the task queue, the event loop runs, it says, oh, I get to do something, pushes the callback on to the stack. Remember it's the stack is like JavaScript land, back inside V8, the callback appears on the stack, run, console.log “there”, and we're done.
Mike: So what are the Benefits of events loop?
Me:
JavaScript events loop enables a developer to build their system around a collection of asynchronously-fired callbacks, freeing the runtime to handle concurrent operations while waiting on external events to happen.
Mike: Wow, this Is more clear now. Thanks.
Me: You are welcome
Top comments (0)