Execution order of multiple setTimeout() functions with same interval
The Spec is here.
My interpretation of setTimeout
step 8 in section 7.3 is that the execution order is supposed to be guaranteed.
However, I investigated this issue because when the window is minimized and then maximised in Chrome, I was finding that timeouts set in events coming from external sources (like websockets or webworkers) were being executed in the wrong order. I assume this is a browser bug and will hopefully be fixed soon.
Play around with this in your fiddle
$(document).ready(function() {
setTimeout(function() {
$("#output").append(" one ");
}, 1000);
});
$(document).ready(function() {
setTimeout(function() {
$("#output").append(" two ");
}, 999);
});
And you will see that both
output: one two
output: two one
are possible. So Speransky is right that you cannot rely on your timeouts executing in the same order always.
Note that I have change one time with 1ms to show that the timeout 1000ms can execute before the 999ms timeout.
EDIT: The below code can delay execution without any chance of two
to be printed before one
function(){
setTimeout(function() {
$("#output").append(" one ");
setTimeout(function() {
$("#output").append(" two ");
}, 100);
}, 1000);
}