This is with regard to how setTimeout
executes its callbacks.
I have have the following
function f1 (argument) {
console.log('f1 start');
for(var i = 0; i < 100000; ++i)
for(var j = 0; j < 10000; ++j);
console.log('f1 complete');
}
function f2 (argument) {
console.log('f2 start');
for(var i = 0; i < 1000; ++i)
for(var j = 0; j < 10000; ++j);
console.log('f2 complete');
}
function f3 (argument) {
console.log('f3 start');
for(var i = 0; i < 10000; ++i)
for(var j = 0; j < 10000; ++j);
console.log('f3 complete');
}
setTimeout(f1,0);
setTimeout(f2,0);
setTimeout(f3,0);
console.log('In main2');
Output:
In main2
f1 start
f1 complete
f3 start
f3 complete
f2 start
f2 complete
John Resig explains in his article, setTimeout
queues all the callbacks until the current block of code completes its execution. This StackOverflow answer explains even though it appears as if the events are fired immediately, they are actually queued.
In the above code you'd notice, f1()
is the longest, followed by f3()
and then f2()
.
My question is, why the observed order(f1
first, then f3
and finally f2
)? If the events are queued, it should simply be in the same order as they were called (f1
,f2
,f3
). How and why does the JavaScript engine pick the longest job first?
[EDIT] Note: The above code was run in Node.js