是否使用setTimeout(fn,0)推迟代码执行,直到当前调用堆栈可靠? [英] Is using setTimeout(fn, 0) to defer code execution until after the current call stack reliable?

查看:68
本文介绍了是否使用setTimeout(fn,0)推迟代码执行,直到当前调用堆栈可靠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个被称为未知次数的函数。我需要知道函数运行了多少次,所以我正在做:

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()在队列上放置一个函数,在所有其他功能都已运行时执行。

setTimeout() places a function on the queue, which is executed when all the other functions have been run.

如果在调用<之前调用 setTimeout()几次code> increment(),您可能会注意到 i 变量达到大于1的值。

If you call setTimeout() a few times before calling increment(), you will probably notice the i variable reaching a value greater than 1.

这篇关于是否使用setTimeout(fn,0)推迟代码执行,直到当前调用堆栈可靠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆