javascript - setTimeOut() 或 setInterval() 。 4 种方法来应用相同的东西。哪个最好?

标签 javascript jquery settimeout setinterval anonymous-function

我正在显示关于给定结束时间的倒计时 watch 。

虽然它工作完美,但我想知道哪种是最好的应用方法。

下面是我的倒计时功能。

  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);
               }
            }); 
     }

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

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

方法 1:使用 setInterval() 和 window 对象

window.setInterval(countdown, 1000);

方法二:独立使用setInterval()

setInterval(function() {countdown()}, 1000);

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

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

function clockStart() {  
        if (timerId) return
        countdown();
}
clockStart(); // calling this function 

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

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

请告诉我

  • 每种方法的优缺点是什么?哪种方法最好/正确?
  • 我应该使用 clearTimeOut() 还是 clearInterval()

引用资料

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

Calling a function every 60 seconds

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

最佳答案

我不会使用您的任何方法。原因是setTimeoutsetInterval do not guarantee that your code will execute after the specified delay .这是因为 JavaScript 是单线程的。

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

使用增量计时的优点是您的代码将执行更接近您指定的固定时间间隔。它会 self 纠正。创建和使用增量计时器很简单。比如你的代码会这样写:

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

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

var start = timer.start();

上面的 delta timer 比 setInterval(方法 1)更好,利用了 setTimeout(方法 2)但也 self 纠正,使用函数启动定时器(方法 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;
};

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

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

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

因此 var timer = DeltaTimer.spawn(funct, delay); 等同于 var interval = setInterval(funct, delay);timer.stop (); 等同于 clearInterval(interval);。我想这就是您可以实现自动化的最大程度了。

关于javascript - setTimeOut() 或 setInterval() 。 4 种方法来应用相同的东西。哪个最好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11520834/

相关文章:

sql-server - 如何为特定的 sql 查询设置超时?

javascript - 在 AngularJS 中 setTimeout 之前显示标签

java - 更改下拉选项

Jquery 使用 Coldfusion 自动完成

jquery - 上传表单数据: Why jquery won't send parameters via post?

javascript - 无法在闭包之外返回值

JavaScript setTimeout 0 阻塞页面渲染?

javascript - 如何将 JSON 对象传递给 Angular 自定义元素

javascript - 字符串的展开运算符

javascript - 用括号调用时 TypeError 不是函数