选项卡未处于活动状态时,Javascript setInterval 无法正常工作

zar*_*aaa 2 javascript jquery setinterval

function initTimer(timeLeft) {
     var Me = this,
     TotalSeconds = 35,
     Seconds = Math.floor(timeLeft);

     var x = window.setInterval(function() {
         var timer = Seconds;

         if(timer === -1) { clearInterval(x); return; }

            $('#div').html('00:' + (timer < 10 ? '0' + timer : timer));
            Seconds--;

         },1000);
     }
Run Code Online (Sandbox Code Playgroud)

我有这个代码。一切正常,当此选项卡在浏览器中处于活动状态时,但是当我更改选项卡并稍后返回选项卡时,它会出现问题。更准确地说,它错误地显示了时间。

我也试过 setTimeout,但问题是一样的。

我的一个想法是:HTML5 Web Workers ...

但这里有另一个问题...浏览器支持。

有人可以帮助解决这个问题吗?即使选项卡未处于活动状态,我如何编写可以正常工作的 setInterval

Mat*_*and 6

使用Date对象来计算时间。当您要求时不要依赖计时器触发(它们不是实时的),因为您唯一的保证是它不会在您要求之前触发。它可能会在很晚之后触发,尤其是对于非活动选项卡。尝试这样的事情:

function  initTimer(periodInSeconds) {
            var end = Date.now() + periodInSeconds * 1000;


            var x = window.setInterval(function() {
                var timeLeft = Math.floor((end - Date.now()) / 1000);

                if(timeLeft < 0) { clearInterval(x); return; }

                $('#div').html('00:' + (timeLeft < 10 ? '0' + timeLeft : timeLeft));
            },200);
        }

initTimer(10);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>
Run Code Online (Sandbox Code Playgroud)

请注意,通过更频繁地检查它,我们可以确保它永远不会偏离太多。