setTimeOut()或setInterval().4种方法同样适用.哪个最好?

diE*_*cho 5 javascript jquery anonymous-function settimeout setinterval

我正在显示一个关于给定的终结时间的倒计时表.

虽然它的工作完美,但我想知道哪种方法最适用.

下面是我的倒计时功能.

  var timerId;
  var postData = {endDate : endDate, tz : tz};  
  var countdown = function()
    { 
      $.ajax({
               type : 'post',
               async : false,
               timeout : 1000,
               url : './ajax_countdown.php',
               data : $.param(postData),
               dataType : 'json',
               success : function (resp){
                  $('#currentTime').html(resp.remainingTime);
               }
            }); 
     }
Run Code Online (Sandbox Code Playgroud)

我想要的是每1秒后自动调用一个函数(倒计时),如果它在1秒内没有执行/完成,则取消当前的ajax并启动一个新的ajax调用.

现在我发现有4种工作方法

方法1:将setInterval()与window对象一起使用

window.setInterval(countdown, 1000);
Run Code Online (Sandbox Code Playgroud)

方法2:独立使用setInterval()

setInterval(function() {countdown()}, 1000);
Run Code Online (Sandbox Code Playgroud)

方法3:在函数内部使用setTimeOut调用其他函数初始化main函数

var countdown = function() { 
     $.ajax({ //ajax code });
     timerId = setTimeout(countdown, 5000); // assign to a variable
 }

function clockStart() {  
        if (timerId) return
        countdown();
}
clockStart(); // calling this function 
Run Code Online (Sandbox Code Playgroud)

方法4:使用匿名函数调用

var countdown = function() { 
     $.ajax({ //ajax code });
     timerId = setTimeout(countdown, 5000);
 }
  (function(){
         if (timerId) return;
         countdown();
})();
Run Code Online (Sandbox Code Playgroud)

请告诉我

  • 什么是每种方法的con和pro,哪种是最佳/正确的方法?
  • 我应该使用clearTimeOut()clearInterval()

参考

http://javascript.info/tutorial/settimeout-setinterval

每60秒调用一次函数

http://www.electrictoolbox.com/using-settimeout-javascript/

Aad*_*hah 7

我不会使用你的任何方法.原因是setTimeout并且setInterval 不保证您的代码将在指定的延迟后执行.这是因为JavaScript是单线程的.

如果我需要在指定的延迟后只调用一次函数,那么我就使用了setTimeout.但是如果我需要在固定的时间间隔之后调用一个函数,那么我就不会使用了setInterval.相反,我使用delta时序.这是代码.

使用增量计时的优点是您的代码将执行更接近您指定的固定时间间隔.它纠正了自己.创建和使用增量计时器很简单.例如,您的代码将按如下方式编写:

var timer = new DeltaTimer(function (time) {
    $.ajax({
        // properties
    });

    if (time - start >= 5000) timer.stop();
}, 1000);

var start = timer.start();
Run Code Online (Sandbox Code Playgroud)

上面的delta计时器优于setInterval(方法1),使用setTimeout(方法2)但也自我纠正,使用函数启动计时器(方法3),并且不使用特殊clockStart函数污染范围(方法4) .

此外,您可以轻松获得定时器启动后调用函数的确切时间,因为调用函数的时间作为参数传递给函数.计时器还有一个stop停止计时器的方法.再次启动它再次呼叫start.

编辑:

如果你想DeltaTimer看起来更像setInterval(自动启动计时器)你可以实现如下的spawn函数:

DeltaTimer.spawn = function (render, interval) {
    var timer = new DeltaTimer(render, interval);

    var start = timer.start = function (start) {
        return function () {
            render.start = start();
        };
    }(timer.start);

    start();

    return timer;
};
Run Code Online (Sandbox Code Playgroud)

然后您可以自动创建并启动DeltaTimer如下:

var timer = DeltaTimer.spawn(function countdown(time) {
    $.ajax({
        // properties
    });

    if (time - countdown.start >= 5000) timer.stop();
}, 1000);
Run Code Online (Sandbox Code Playgroud)

因此var timer = DeltaTimer.spawn(funct, delay);等同于var interval = setInterval(funct, delay);timer.stop();等效于clearInterval(interval);.我想这就像你可以自动化它一样多.


Mat*_*att 6

使用#1而不是#2的好处是window引用消除了范围变量覆盖的可能性setInterval.

// When out of global scope...
function setInterval() {

}

window.setInterval(foo, 100); // still calls the "correct" setInterval
Run Code Online (Sandbox Code Playgroud)

countdown在函数中包装调用之间没有区别(#1,#2).#2为您提供了更大的灵活性,因为您也可以调用其他函数/传递参数等(尽管如果情况如此,从#1交换到#2显然是微不足道的).

#4保存你必须声明一个函数clockStart,除此之外,它与#3相同.

使用,clearTimeout如果您使用setTimeout,clearInterval如果您使用setInterval...

你也应该知道如何setTimeoutsetInterval工作方式不同.有一个惊人的答案这里这解释了...

至于我用的是什么?我会用#2.