Search code examples
javascriptdom-eventscallstackevent-loop

Initial run through of a JavaScript file


In Javascript, whenever an asynchronous operation/event is called, a message is created along with the operation/event's callback function (a function which only runs after the operation/event has finished).

When the operation/event is complete (or triggered) the message moves onto a message queue. This message queue is polled constantly (this polling is known as "the event loop") and, when a message is found in the queue, the message's callback is placed on the callstack and run. We then return to the event loop and either wait for a new message or grab the next message in the queue and run its callback.

My question is: before all of this, when a JavaScript file is first run, is everything run on that same callstack before the event loop starts up?


Solution

  • This is a pretty interesting question. Someone will no doubt provide a better explanation as I don't fully understand what is going on, but from my testing I have determined that the answer to your question is no.

    Take the following code example:

    alert( 'start' );
    
    var cats = document.getElementById( 'cats' );
    
    cats.addEventListener('click', function() {
        alert( 'cats' );
    });
    
    cats.click();
    
    alert( 'finish' );
    

    The alerts fire as follows: start, cats, finish. The fact that cats appears before finish proves that message are being added to the event loop as the code is being executed, not after.

    http://jsfiddle.net/3bm2pz86/