当选项卡未处于焦点中时暂停 Javascript 计时器



我要求显示执行某些操作的人数的实时更新。我通过每 20 秒向服务器发出一个 ajax 请求来实现此功能。但是即使选项卡不在焦点中/没有人在查看更新,也会发生此 ajax 请求。有没有办法确定选项卡是否处于活动状态?

我有以下代码(简化版本),但它不起作用。

timer = undefined
$(document).ready ->
  timedCountUpdate()
  window.top.onblur = ->
    clearTimeout(timer)
  window.top.onfocus = ->
    timer = timedCountUpdate()
@timedCountUpdate = () ->
  timer = setTimeout(updateCountIndicator, 20000)
@updateCountIndicator = () ->
  $('.indicator').html = 100
  timedCountUpdate()

即使我不在加载应用程序的选项卡中,我仍然看到每 20 秒拨打一次电话。我正在铬中进行测试。

In Coffeescript w/jquery:

$ ->
  timeout_id = null
  resumeTimer = () ->
    # make ajax call here
    # Prevent multiple timers from operating simultaneously:
    clearTimeout timeout_id if timeout_id?
    # Recursive step (ideally fires in 'success' handler of ajax call)
    timeout_id = setTimeout(resumeTimer, 2000)
  $(window.top).focus () =>
    resumeTimer()
  $(window.top).blur () =>
    clearTimeout timeout_id
  # Start timer immediately:
  resumeTimer()
我知道

这是一个老问题,但我在谷歌搜索中偶然发现了它,并希望提供另一种更适合您想要做的事情的替代方案。

页面可见性 API 是这些类型的事情应该如何向前推进(或现在的 IE10+)。API 提供了一个 visibilityChange 事件,该事件在选项卡的可见性更改时触发。 在回调中,检查 document.hidden 属性将告诉您选项卡是否隐藏。

从那里,清除您的间隔或重新开始。

在您的情况下,我会执行以下操作:

var tab_paused = false; // global
if (typeof window.top.onblur === 'function')
{
    window.top.onblur = function() {
     tab_paused = true;
    };
}
if (typeof window.top.onfocus === 'function')
{
    window.top.onfocus = function() {
     tab_paused = false;
    };
}
if (typeof document.onfocusout === 'function')
{
    document.onfocusin = function() {
     tab_paused = true;
    };
}
if (typeof document.onfocusin === 'function')
{
    document.onfocusin = function() {
     tab_paused = false;
    };
}
var ctx = setInterval(function() {
 if (tab_paused === false)
 {
  $('.indicator').html(100);
 }
}, 100);

最新更新