Suppose I do
setTimeout(foo, 0);
...
setTimeout(bar, 0);
Can I be sure foo will begin executing before bar? What if instead of 0 I use a
The answer is: No, execution order is not guaranteed. I have occasionally seen non-FIFO ordering in chrome 40, especially if I pause in debugger while timeouts are pending. I also had a rare sighting in the wild - it was the only plausible explanation of an incident I investigated.
If you need guaranteed execution order, instead of setTimeout(callback, 0) you can do this:
var queue = [];
function handleQueue() {
queue.shift()();
}
function queueCallback(callback) {
queue.push(callback);
setTimeout(handleQueue, 0);
}
Now, for guaranteed foo, bar order you can:
queueCallback(foo);
...
queueCallback(bar);