An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
Execuion context, Event Loop, callback queue
Explained Async JS in 4min read. ( callback queue & Event Loop )
Post is distributed in 3 parts->
Execution Context
callback Queue
Event Loop
example :
function hireMe(){ console.log(`you are hired`);}setTimeout(hireMe, 0)console.log(`Me First!`)
(1) execution context
As execution starts it will declare a placeholder for hireMe in a global execution context and will store the function definition in it...
As it reaches to setTimeout, it will create a timer in the browser with the given amount of time.
Remember as we invoke a function first it goes to call stack then its execution context is created and it gets destroyed as the function returns something.
The interesting things start from here
(2). Callback queue - let's understand how it works
So what setTimeout will do is, it will add the hireMe function in the callback queue as the timer finishes, which is specifically made for async calls.
Note the function will not be added directly to the call stack as the timer finishes.
callback queue is specifically made for Asynchronous calls
It doesn't matter what time you have specified in setTimeout
(3). Event Loop
Now comes the Event Loop
, which checks the call stack if it's empty or not. If nothing is inside the call stack then the function from the callback queue gets pushed in the call stack.
Event Loop
is an infinite loop which is consistently checking the call stack if it is empty or not.From what we have seen till We can say, functions that are in the
callback
queue need to wait until the whole Global execution gets finished and whether the call stack is empty or not...so you can also have millions of
console.logs()
in the global context and they all will run before thehireMe()
There is one more thing called Microtask queue i will explain it in next post
Original Link: https://dev.to/chait04/execuion-context-event-loop-callback-queue-2aec
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To