SetTimeout function and asynchronous function

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

+4
source share
2 answers

Regardless of the "javascript engine" question (there is no such thing, there is a language specification and different implementations), because it depends (see this other answer ), you can use promises if you want to provide a certain sequence order.

Check out the Q library at https://github.com/kriskowal/q

Or this RSVP library https://github.com/tildeio/rsvp.js

Promises / a + spec here

Available for node and browser

My own test on node v0.10.21 (same as firefox and chromium console):

 ~/workspace/tmp$ node test.js In main2 f1 start f1 complete f2 start f2 complete f3 start f3 complete 
+1
source

I tried my code in the firebug console, and I got the result in the following order, which I think was as expected.

In main2, the start of f1 f1 is completed; the start of f2 f2 is completed; the start of f3 f3 is completed

I am using firefox 12.0 using fedora.

+1
source

All Articles