为什么setInterval()在这段代码中停止得太早?

时间:2015-04-22 22:49:05

标签: javascript setinterval

<div class="wait">Wait</div>
<div class="waitDownloadLink"></div>

$(document).ready(function()
                  {
                      var secondNormal = 40;
                      var refreshIntervalId;
                      refreshIntervalId = setInterval(function() {
                          secondNormal -= 1;
                          $(".wait").text(secondNormal);

                      }, 1000); 
                      setTimeout(function() {
                          clearInterval(refreshIntervalId);
                          $(".waitDownloadLink").text("Click me to download");
                      }, secondNormal * 1000);




                  });

当我开始运行代码并停留在网页上时,代码似乎太完美(或接近)。但是,当我在启动代码后立即在其他网页上浏览时,计时器会在12到18秒之间停留,然后停止运行。为什么会这样?有没有解决方案可以解决这个问题?

https://jsfiddle.net/s1zf18co/

4 个答案:

答案 0 :(得分:1)

浏览器通常会暂停或降低在不可见的选项卡中运行的Javascript的线程优先级。我的猜测是它是笔记本电脑和其他东西的省电措施,但他们都已经做了多年。 This question对此问题进行了非常彻底的调查。

解决方案是使用不会暂停的网络工作者。有关详细信息,请参阅the Mozilla documentation

答案 1 :(得分:0)

有一个可行的解决方案,尝试这个,如果它足够好,可以留下页面问题,在最终条件下编辑。

$(document).ready(function () {
    var secondNormal = 40;

    var refreshIntervalId = setInterval(function () {
        setTimeout(function () {
            if(secondNormal >0) {
                secondNormal -= 1;
            }
        }, 1000)

        $(".wait").text(secondNormal);
    }, 1000);
});

答案 2 :(得分:0)

除了Mordred的回答,在这种情况下,您可以尝试使用JS Date对象来正确估计时间。查看this question

答案 3 :(得分:0)

我似乎无法复制该错误,但我相信使用Date对象可能会修复它:

var getDateTimeInSeconds = function() {
  return Math.floor(Date.now() / 1000)
};

$(document).ready(function() {
  var numOfSeconds = 40;
  var countFrom = getDateTimeInSeconds();
  var countTo = countFrom + numOfSeconds;

  var refreshIntervalId = setInterval(function() {
    var secondsLeft = countTo - getDateTimeInSeconds();
    if (secondsLeft < 0) {
      $(".wait").text(0);
      $(".waitDownloadLink").text("Click me to download");
      clearInterval(refreshIntervalId);
    } else {
      $(".wait").text(secondsLeft);
    }
  }, 1000);

});

小提琴:https://jsfiddle.net/s1zf18co/1/