Set of setTimeout calls with intervals 0,1,2,3.
function f() {
setTimeout(function a() {console.log(10);}, 3);
setTimeout(function b() {console.log(20);}, 2);
setTimeout(function c() {console.log(30);}, 1);
setTimeout(function d() {console.log(40);}, 0);
}
f();
Output: (from chrome. Hope would be the same in other browsers)
30
40
20
10
Can someone explain clearly why is the ordering not 30, 40, 10, 20? It is said browsers maintain a minimum 10ms or (spec says) 4ms interval. If so, validate the output with time metrics or whichever is convenient to explain this behavior. What minute detail am I missing to understand this awesome feature of the language?
Edited:
I know these functions are asynchronous. And I have read John Resig' blog couple of times. And I know a setTimeout' callback is not guaranteed to execute at the interval specified.
To be more precise, I expect an explanation that can explain the behavior in terms of execution queue, event loop, call stacks and timers.
Refer this and this for more details