Asynchronous Callback

  • More than one at a time
  • Javascript is Synchronous : execute one at a time
  • Apart from the Execution Context, we have something called Event Queue:

    • This is thought of events, notifications of event that might be happening, so when the browser somewhere outside the JS Engine has an event that inside the JS Engine, we want to be notified of, it get placed on the Queue
    • Whether or not we have a function that needs to respond to it, we can listen for that event
    • Event Queue get looks after by Javascript when the Execution Stack is empty, so function b, function b , finishes execution at global level -> when the stack is empty the JS looks at the Event Queue:

      • Process the clickHandler -> Creates the Execution Context ... -> Then Http Request

      • So Javascript script is not Asynchronous, the browser is Asynchronous putting thing in the event Queue, then when the execution context is empty, it process the event...etc

Example:

// long running function
function waitThreeSeconds() {
    var ms = 3000 + new Date().getTime();
    while (new Date() < ms){}
    console.log('finished function');
}

function clickHandler() {
    console.log('click event!');   
}
// listen for the click event
document.addEventListener('click', clickHandler);
waitThreeSeconds();
console.log('finished execution');

On Chrome Dev Console:
> finished function
> finished execution
> click event

results matching ""

    No results matching ""