Search code examples
javascriptasynchronouscallbacksettimeoutnest

how nested setTimeout method gets executed in sequence?


    setTimeout(() => {
        console.log(1);
        setTimeout(() => {
            console.log(2);
            setTimeout(() => {
                console.log(3);
            }, 1000);
        }, 1000);
    }, 1000)

Why this code allows you to console.log in every second sequentially? I expected the code would run 1, 2, 3 at the same time since all the timers were set to 1000 millisecond.


Solution

  • Delay argument passed to setTimeout is the minimum amount of time it will take before the callback function is executed; it's not the actual time at which the callback will run.

    Callbacks run in the order in which their timer expires and they get pushed into the task queue. From the task queue, they get pushed on to the call stack when the stack is empty.

    Callback that is pushed first in the task queue is the first to get pushed on to the call stack. Consequently it is the first to get executed.

    Why this code allows you to console.log in every second sequentially?

    That's because each inner setTimeout callback also needs to account for the delay of the wrapper setTimeout.

    The callback function of the second setTimeout has a delay of 2 seconds because the second setTimeout is called after the first timer expires after 1 second.

    Similarly, the inner most setTimeout has a delay of 3 seconds.