DEV Community

Cover image for How javaScript Asynchronous works under the hood?
Sam aghapour
Sam aghapour

Posted on

How javaScript Asynchronous works under the hood?

in this brief Article I'm going to show you how Event loop , Call stack , Callback queue and web APIs (Events table) work together and handle the asynchronous and synchronous functions. ok let’s dive into it.

Image description
in the above gif, it shows how functions orderly go to to call stack and after execution they pop out of it and one intresting thing that catches your attention is that asyncronous setTimeout function which is not gonna end up right here (we’ll talk about it more), but first let break the gif down into a few parts to see what exactly going on:
greet function is called
this function goes to call stack to run
now call stack executes this function and return “hello”
greet function pops out of call stack
now respond function goes the same way above
that’s it for the gif, let’s continue…

Web APIs ( Events table ) , Callback Queue , Event Loop

Introducing of Web APIs(Event tables) :

every functions that is asynchronous like Ajax , setTimeouts , event handlers , etc.., join to Events table and wait for the time for execution to come, for example: setTimeout waits 3000 ms to run or event handler waits untill Click event happens and then run. as we know functions are executedin call stack but these guys can’t join the others in call stack yet, so… they should go somewhere else but wher?!

Introducing of Callback Queue :

as it’s called , this is a queue of callbacks (the gusy in the events table, remember?), thus callbacks which are waiting for get executed will join to this queue. this queue is not going to execute callbacks or even push them to call stack so what it does?!

Introducing of Event loop :

This dude is an intermediary between web APIs and callback queue , what does it mean?
event loop waits and keeps an eye on call stack and callback queue and when call stack is emty and there is no synchronous function to execute , event loop takes first callback from callback queue and sends it to call stack and as usual, call stack will execute it just like other functions.
now we know how any of these works, let’s see it in the gif below to understand this cooperate better.
attention: watch this gif twice ,first time just look at bar function and its setTimeout and second time look at the rest of the functions which are synchronous.

Image description
let’s see above gif as a code now:

Image description

now we can see although bar function gets called first but because it’s asynchronous it has to wait for synchronous guys to get executed first, it is good to know that if setTimeout time was even 0 ms it wouldn’t be change anything , it’s ashnchronous function afterall.
well , that’s pretty much it
now , you are a better programmer than 10 minutes ago.

goodbye and good luck.🤞

Top comments (0)