简体   繁体   English

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

[英]Javascript setInterval doesn't work correctly when tab is not active

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

I have this code.我有这个代码。 Everything works fine, when this tab is active in browser, but when I change tab and return in tab later it has problems.一切正常,当此选项卡在浏览器中处于活动状态时,但是当我更改选项卡并稍后返回选项卡时,它会出现问题。 To be more precise, it Incorrectly displays the time.更准确地说,它错误地显示了时间。

I'd also tried setTimeout, but problem was the same.我也试过 setTimeout,但问题是一样的。

One idea, which I have is: HTML5 Web Workers...我的一个想法是:HTML5 Web Workers ...

But here is another problem... browsers support.但这里有另一个问题...浏览器支持。

can someone help to solve this problem?有人可以帮助解决这个问题吗? How can I write setInterval, which works properly,even when tab is not active即使选项卡未处于活动状态,我如何编写可以正常工作的 setInterval

Use the Date object to calculate time.使用Date对象计算时间。 Don't rely on a timer firing when you ask it to (they are NOT real-time) because your only guarantee is that it'll not fire before you ask it to.当您要求时不要依赖计时器触发(它们不是实时的),因为您唯一的保证是它不会您要求之前触发。 It could fire much later , especially for an inactive tab.它可能会在很晚之后触发,尤其是对于非活动选项卡。 Try something like this:尝试这样的事情:

 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);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="div"></div>

Note that by checking it more frequently we can make sure it's never off by too much.请注意,通过更频繁地检查它,我们可以确保它永远不会偏离太多。

JavaScript timers are not reliable, even when the tab is active . JavaScript 计时器不可靠,即使选项卡处于活动状态 They only guarantee that at least as much time as you specified has passed;他们只保证至少你指定的时间已经过去; there is no guarantee that exactly that amount of time, or even anything close to it, has passed.不能保证确切的时间量,甚至任何接近它的时间,已经过去了。

To solve this, whenever the interval fires, note what time it is .为了解决这个问题,每当间隔触发时,请注意它是什么时间 You really only need to keep track of two times: the current time, and the time that the previous interval fired.您实际上只需要跟踪两次:当前时间和前一个间隔触发的时间。 By subtracting the previous tick's time from the current tick's time, you can know how much time has actually passed between the two, and run your calculations accordingly.通过从当前刻度的时间中减去前一个刻度的时间,您可以知道两者之间实际经过了多少时间,并相应地运行您的计算。

Here's a basic outline of how something like this might look:以下是类似内容的基本轮廓:

function  initTimer(timeLeft) {
        var Me           = this,
            TotalSeconds = 35,
            Seconds      = Math.floor(timeLeft),
            CurrentTime  = Date.now(),
            PreviousTime = null;

        var x = window.setInterval(function() {
            var timer = Seconds,
                timePassed;
            PreviousTime = CurrentTime;
            CurrentTime = Date.now();
            timePassed = CurrentTime - PreviousTime;

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

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

        },1000);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM