Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 7, 2021 04:49 pm GMT

Execuion context, Event Loop, callback queue

Explained Async JS in 4min read. ( callback queue & Event Loop )

Post is distributed in 3 parts->

  1. Execution Context

  2. callback Queue

  3. 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 the hireMe()

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

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To