Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

settimeout - Are equal timeouts executed in order in Javascript?

Suppose I do

setTimeout(foo, 0);

...

setTimeout(bar, 0);

Can I be sure foo will begin executing before bar? What if instead of 0 I use a timeout of 1, 10, or 100 for bar?

Simple experiments show that in the case of equal timeout values the timeout targets are executed in the same order as the setTimeouts themselves, but is it safe to rely on this behavior?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is not safe to rely on this behavior. I wrote a test script which schedules a number of functions (and they in turn also schedule a number of functions) all using setTimeout(..., 0), and the order in which the functions were called was not always the same as the order in which setTimeout was called (at least in Chrome 11, which I used to run the script).

You can see/run the script here: http://jsfiddle.net/se9Jn/ (the script uses YUI for cross-browser compatibility, but Y.later uses setTimeout internally).

Note that if you just run the script and stare at the console, you will probably not see an offending ordering. But if start the script, switch to another tab, load some pages, and come back to the test page, you should see errors about callbacks out of order in the console.

If you need a guaranteed ordering, I would recommend scheduling the next function at the end of the previous function:

setTimeout(foo, 0);

...

function foo() {

    ...

    setTimeout(bar, 0);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...