The Event Loop

The Event Loop Behavior

What's the execution order of this code?

var value;

setTimeout(function () {
    value = 'VALUE';
}, 100 /* 100 ms. */);

console.log(value); // ???

setTimeout(function () {
    console.log(value); // ???
}, 200);

And in this case?

function main() {

    var value;

    setTimeout(function () {
        value = 'VALUE';
    }, 0 /* 0 ms. */);

    console.log(value); // ???

    setTimeout(function () {
        console.log(value); // ???
    }, 0);
    
    console.log(value); // ???

}

main();

How the event loop works

  1. Register a listener : Most asynchronous tasks requires the definition of a callback function in order to retrieve the result of the processing or simply in order to know that the processing ended. During this step, we explicitly or implicitly subscribe a listener to some event source. Examples: setTimeout, addEventListener etc...

  2. Add the function to the queue: The callback function cannot be called immediately when the result is received as the thread might be busy executing another function. In the example below, both callback functions are ready to be called the thread is busy executing our main function. The JavaScript engine adds references to the callback functions at the end of the callback queue in order to be called once the thread is free.

  3. Tick : When the main function execution ends, the thread won't have time to stay idle and will immediately grab the callback at the top of the queue and execute it. More precisely, this is the event loop which simply loops forever executing every function in the queue. The moment where the event loop ends the execution of a function and is ready to grab the next one is called a "tick".

Last updated