JavaScript is a single-threaded synchronous language. JS engine uses call-stack to manage execution. but what if we have to perform asynchronous task?
Event Loop
In case of event listeners
document.getElementById("btn").addEventListener("click", function cb() {
console.log("callback");
});
for above code; when this line is executed,
- Web API (window object) attaches click event listener to the callback function and pushes this callback to the callback queue upon occurrence of event “click”.
- Event loop constantly check call stack and callback queue, if there is a callback in callback queue, it pushes to stack to execute it.
In case of fetch() API
fetch("http://api.netfilex.com)
.then(function cbf(){
console.log("cb netfilx")
})
- web API’s environment registers callback function
cbf
- callback goes to Micro-task queue( same as callback queue but is has higher priority).
What can come inside micro-task queue
Promises and mutation observers goes inside micro-task queue.
Starvation
suppose there is endless callbacks in micro-task queue, so callback queue’s function is never executed. this is starvation.