Skip to main content
0:01est. 3 min

Chapter 18- What about Asynchronous Callbacks

Notes

#BIGWORD Asynchronous - More than one at a time
Rendering engine <-> The javascript engine <-> HTTP request
It happens asynchronously inside browser but synchronously inside javascript engine.
How this happens inside js engine?
There is an execution stack and event queue like click event and the HTTP request is placed in queue. The event queue is looked at by javascript when the execution stack is empty
Once the execution stack is empty then js periodically looks at the event queue and waits for something to be there and check if this function to executed once the event was triggered
So it sees click event it processes clickHandler() and creates the execution context for that function once that function is processed next item in the queue moves up. It will not get processed until the execution stack is empty.
It's not asynchronous actually, browser is putting things in queue asynchronously but the code is running line by line and when execution stack is empty it processes event in queue..
Example 1 - How callbacks work
function waitThreeSeconds(){
var ms = 3600 + new Date().getTime();
while(new Date() < ms) {}
console.log("Finished function");
}

function clickHandler(){
console.log("Click event");
}

document.addEventListener("click",clickHandler);

waitThreeSeconds();
console.log("Finished execution");