There is a possibility that my code can defer two or more functions in short succession. Can I guarantee that each deferred function will execute in the order in which I created them? For my web application on iOS 5 & 6, the correctness of my code relies on deferred functions being executed in order.
I am using Prototype's defer, which is implemented using a timeout of 0.01 seconds.
A "deferred" function will not run immediately; rather, it will run as soon as the interpreter's call stack is empty.
From my own testing, it seems that they are executed in the order which I create them. The following did print out all the integers from 0 to 99 in order.
Test Code
for (var i = 0; i < 100; i++) {
(function(x) {
return function() {
console.info(x);
}
})(i).defer();
}
Output
0
1
2
...
88
99
However, this result is not conclusive. I have no idea how it behaves with deeper functions or different CPU loads.