Search code examples
javascripttimeoutqueue

Javascript - run time priority and queue


if i do:

setTimeout(function(){ alert('antani'); },400);
    setTimeout(function(){ alert('supercazzola'); },400);

why does this script generates queue between these two timeouts?

Shouldn't they alerted in same moment?

as i can see testing it out, first, the first alert is executed, then the second.


Solution

  • Background

    JavaScript has only the one thread in which the interpreter is running. This means that events are never processed at the same time. When you set a timeout you actually subscribe to some internal event of the browser that fires each time browser is in the idle mode (when not busy with rendering, parsing or executing some script, etc.). The handlers of this event as well as time they were scheduled are posted to the queue according to the order setTimeout appeared in the script. Each time this internal event is fired, the browser checks each handler and decides whether to execute and remove it from the queue or to skip it.

    Same Time

    When you schedule the tasks one after another with the same estimation time

    setTimeout(function(){ $('.element').hide(); },400);
    setTimeout(function(){ $('.element').show(); },400);
    

    the .element will be first hidden and then shown. Note that it does not mean that the browser will render the change to .element after it's hidden. Most browsers will only render after the script has finished executing.

    Different Time

    When you schedule tasks with different estimation times:

    setTimeout(function(){ $('.element').hide(); },401);
    setTimeout(function(){ $('.element').show(); },400);
    

    the result may be unpredictable. The following cases may occur:

    • more or equal to 400 and less than 401 milliseconds have passed and browser is starting to process event handlers. In this case .element will first be shown and then hidden. Note that there may be other setTimeouts scheduled to be executed after 400 milliseconds and they will run prior to the hide .element.

    • browser was busy for 401 milliseconds or more before it first starts to process event handlers. In this case most likely (depending on browser implementation) the .element will first be hidden and then shown, despite the fact that according to estimation time it should be vice versa!

    Regarding your question: is it the same to set timeouts with the same time or some positive delta the answer is NO. It is not the same, when you set timeouts with delta there is always a possibility that another event or timeout will be processed between them.