How Async Works
How Async Works
Example -1
Javascript
console.log("Line1");
setTimeout(function callback1(){
console.log("Line3");
},3000);
console.log("Line6");
Output
Line1
Line2
Line3
To understand how this code works out we need to understand the event
loop and callback queue
Event Loop
In JavaScript, an event loop is a mechanism that enables asynchronous
programming. The event loop works by continuously processing a queue
of events and executing any associated callbacks or functions.
Callback Queue
In JavaScript, the callback queue is a mechanism used by the event loop
to manage asynchronous code execution. Whenever an asynchronous
operation is performed, such as a timer set by setTimeout() or an HTTP
request made by fetch(), the associated callback function is added to the
callback queue.
The event loop constantly monitors the callback queue and executes the
callbacks in the order in which they were added, one at a time. This
ensures that the JavaScript runtime remains single-threaded and that no
two callbacks are executed simultaneously.
Example 2
Javascript
console.log("lets Start"); // line1
const btnAddtoCart = document.getElementById("btn"); //line2
btnAddtoCart.addEventListener("click",()=> { //line3
console.log("Button Clicked");
});
console.log("Bye Bye ......");
Let us try to understand the execution of the code above line by line.
The callback queue is the queue which is also known by the name task
Queue but we also have a queue named microTask queue.
All the promised-based callbacks are registered inside the microtask
queue and have the highest priority and all the other types of callback are
pushed into the callback queue or the task queue as it have less priority
then the microtask queue.