Search code examples
javascripttimerdom-events

setTimeout doesn't start instantly


When I put the following function in the head of my document :

(function(){
    var d = new Date().getTime();
    console.log(new Date().getTime() - d);

    window.setTimeout(function(){
        console.log(new Date().getTime() - d)
    }, 1);

    window.setTimeout(function(){
        console.log(new Date().getTime() - d)
    }, 10);

    window.setTimeout(function(){
        console.log(new Date().getTime() - d)
    }, 100);

    window.setTimeout(function(){
        console.log(new Date().getTime() - d)
    }, 1000);
}());

I have these logs :

0
401
401
402
1397

There seems to be a delay of 400ms before the setTimeout starts. Why?


Solution

  • Javascript is not multi-threaded - setTimeout does not start instantly. All that happens when you call setTimeout is it puts that function onto a queue to be executed when the current execution stack unwinds. In your case, it is taking about 400 ms to get to that point.

    See How Timers Work for a good tutorial on this. In particular, this quote is relevant:

    In order to understand how the timers work internally there’s one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there’s been an opening in the execution.