Search code examples
javascriptnode.jsv8event-loop

Javascript Asynchronous with setTimeout(..., 0)


I wanted to have a better understanding of how the event loop and asynchronous code works in Javascript. There is a ton of resources online but I could not find an answer to my question

Everyday I mostly use callbacks, promises, async/awaits, but at the end I am simply relying on already asynchronous methods.

Therefore I wanted to know how it works, creating an async function from scratch, and deal with blocking code (or should I say slow code, that is not an HttpRequest or anything that is already provided to us).

For example taking while loop with a very high condition to stop it, should take a second to finish. And this is what I decided to implement for my tests.

After my research, I could read that one way of making my code asynchronous, would be to use setTimeout with a 0ms delay (placing a message in the event queue, that will be executed after the next tick)

function longOperation(cb) {
    setTimeout(function() {
        var i = 0;
        while (i != 1000000000) { i++; }
        cb();
    }, 0);
}

longOperation(() => {
    console.log('callback finished');
})

console.log('start');

My question is:

When my code is finally going to be executed, why isn't it blocking anymore ? What is the difference between executing it normally, and placing a message that the event loop will pick to push it to the call stack ?

The following video shows how the event loop handles a setTimeout with 0 delay.

JavaScript Event loop with setTimeout 0

However, the code executed is a simple console log. In my example, this is a "long" operation...


Solution

    1. The outer code executes to completion.
    2. The setTimeout 0 timer expires immediately, so its callback runs right away and executes to completion (the long-running while loop and its callback).

    During both of these code execution phases, no other JavaScript user code will run.