如何重写替代的$ setTimeout函数,以便更容易阅读?

时间:2016-10-31 17:02:25

标签: javascript angularjs

最初,在AngularJS中,我有一个我想定期调用的函数。所以,我使用$setInterval函数来做到这一点。但是,在这样做的时候,我注意到即使离开页面,该功能仍然继续运行并完全填满我的控制台,直到我导航回与该功能相关的页面。我用我发现here的解决方案替换了我的$setInterval函数。这家伙写了$setInterval的全新版本。它看起来像是:

function interval(func, wait, times) {
    var interv = function(w,t){
        return function(){
            if(typeof t === "undefined" || t--> 0){
                setTimeout(interv, w);
                try{
                    func.call(null);
                }catch(e){
                    t = 0;
                    throw e.toString();
                }
            }
        };
    }(wait,times);
    setTimeout(interv,wait);
};

我基本上将我的功能称为:

interval($scope.setValue, 100);

此功能完全按照我的意愿工作,我们的先前问题已得到解决。但是现在,可读性已经成为一个问题,我想知道是否有一种方法可以重写这个函数,以便它更容易阅读(可能代码更少)但功能却相同?

1 个答案:

答案 0 :(得分:0)

以下是对它的看法,为了清晰起见,这些评论看起来更长,尽管它不是:

function interval(func, wait, times) {
    // Set `t` to either Infinity or the number of times we're supposed to repeat
    var t = typeof times == "undefined" ? Infinity : times;

    // The tick function we call
    function tick() {
        // Set up the next iteration if appropriate
        // Note that --Infinity is Infinity, so it will never stop in that case
        if (--t > 0) {
            setTimeout(tick, wait);
        }

        // Call the function, canceling further repeats if it throws an exception
        try {
            func.call(null); // Or just func() seems like it should be good enough, really
        } catch(e) {
            t = 0;
            throw e;
        }
    }

    // Start the process
    setTimeout(tick, wait);
}

这保留了当前函数的一些行为,这些行为与标准setInterval不同(我不能代表Angular')

  • 如果函数失败一次
  • ,它将停止尝试调用该函数
  • 它有一个功能,让您指定调用该功能的最大次数(这看起来很方便)