Execution order of multiple setTimeout() functions with same interval

Viewed 49438

Consider the following Javascript code:

function(){
    setTimeout(function() {
        $("#output").append(" one ");
    }, 1000);
    setTimeout(function() {
        $("#output").append(" two ");
    }, 1000);
}

You can also see this example on jsfiddle.

Can I be sure that the value of #output is always "one two", in that order? Usually, I would handle this problem like this:

function(){
    setTimeout(function() {
        $("#output").append(" one ");
        $("#output").append(" two ");
    }, 1000));
}

But I can not do it that way because I get messages from a server which tells me which function to execute (in this example append "one" or append "two"), which I have to execute with a small delay.

I already tested this code in Internet Explorer 9, Firefox 14, Chrome 20 and Opera 12, and the output was always "one two", but can I be sure that this will always be the case?

9 Answers

It depends on the browser, because setTimout is part of the window object in the browser, not defined in ECMAScript.

Per spec, the have the same task source, and things that have the same task source should be ordered. So yes.

Related