setTimeout(fn,0)和setTimeout(fn,1)有什么区别? [英] What is the difference between setTimeout(fn, 0) and setTimeout(fn, 1)?
问题描述
jQuery来源结合使用setTimeout
和1
作为第二个参数.我的印象是,它们都意味着尽快执行功能".
The jQuery source features uses of setTimeout
with both 0
and 1
as second argument. I'm under the impression that they both mean "execute the function as soon as you can".
这是正确的吗?两者之间有区别吗?
Is this correct? Is there a difference between the two?
推荐答案
我认为答案是取决于".现在.
I think the answer is "It depends" now.
我们可以在不同的平台和浏览器中运行代码:
We can run the code in different platform and browsers:
function setTimeouts() {
setTimeout(function() { console.log(2); }, 2);
setTimeout(function() { console.log(1); }, 1);
setTimeout(function() { console.log(0); }, 0);
}
for (var i = 0; i < 10; i++) {
setTimeouts();
}
For Node.js,
0
is converted to1
, so they are exactly the same: https://github.com/nodejs/node/blob/master/lib/timers.js#L319, and result might be:
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
2
2
2
2
2
2
2
2
2
2
对于Chrome,结果与Node.js非常相似
For Chrome, the result is quite similar with Node.js
对于Firefox,大多数0
都将在1
之前打印:
For Firefox, most of 0
will be printed before 1
:
0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
2
2
2
2
2
这篇关于setTimeout(fn,0)和setTimeout(fn,1)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!