[英]Is using setTimeout(fn, 0) to defer code execution until after the current call stack reliable?
I've got a function that is called an unknown number of times. 我有一个被称为未知次数的函数。 I need to know how many times the function was run so I'm doing: 我需要知道函数运行了多少次,所以我正在做:
(function () {
var i = 0,
increment = function () {
if (i === 0) {
setTimeout(function () {
console.log('increment was called ' + i + ' times.'); // increment was called 3 times.
i = 0;
}, 0);
}
i++;
};
increment();
increment();
increment();
})();
Can anyone tell me whether this is reliable across all browsers or whether there's a better pattern to achieve this? 任何人都可以告诉我这是否在所有浏览器中都是可靠的,或者是否有更好的模式来实现这一目标?
setTimeout()
places a function on the queue, which is executed when all the other functions have been run. setTimeout()
在队列上放置一个函数,该函数在运行所有其他函数时执行。
If you call setTimeout()
a few times before calling increment()
, you will probably notice the i
variable reaching a value greater than 1. 如果在调用increment()
之前调用setTimeout()
几次,您可能会注意到i
变量的值大于1。
Yes this code snippet seems to be reliable across all browsers even in the lowest version of IE. 是的,即使在最低版本的IE中,此代码段似乎在所有浏览器中都是可靠的。 I tried this in IE8 I works good. 我在IE8中试过这个我工作得很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.