This refers to how setTimeout
executes its callbacks.
I 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');
Exit:
In main2
f1 start
f1 complete
f3 start
f3 complete
f2 start
f2 complete
John Resig explains in his setTimeout
article the queues of all callbacks until the current block of code completes. This answer is stackoverflow explains, even if it looks like events are triggered immediately, they are actually queued.
In the above code, you will notice that f1()
is the longest, followed by f 3()
, and then f2()
.
My question is: why is the observed order ( f1
first, then f3
and finally f2
)? If events are queued, they should simply be in the order in which they were called ( f1
, f2
, f3
). How and why does the JavaScript engine first choose the longest job?
[EDIT] Note: The above code was run in Node.js
source share