选项卡处于非活动状态时,Javascript setInterval无法正常工作 [英] Javascript setInterval doesn't work correctly when tab is not active

查看:141
本文介绍了选项卡处于非活动状态时,Javascript 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);
     }

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

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.

我也尝试过setTimeout,但是问题是相同的.

I'd also tried setTimeout, but problem was the same.

我有一个想法:HTML5 Web Workers ...

One idea, which I have is: HTML5 Web Workers...

但这是另一个问题……浏览器支持.

But here is another problem... browsers support.

有人可以帮助解决这个问题吗? 我该如何写setInterval,即使tab处于不活动状态也能正常工作

can someone help to solve this problem? How can I write setInterval, which works properly,even when tab is not active

推荐答案

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

Use the Date object to calculate time. 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 setInterval无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆