递归setTimeout()在后台暂停 [英] recursive setTimeout() pause on background

查看:456
本文介绍了递归setTimeout()在后台暂停的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码:

var logo = $("#blinking-logo");
function logo_blink() {
    logo.fadeOut(10).delay(10)
        .fadeIn(10).delay(20)
            .fadeOut(10).delay(10)
            .fadeIn(10)
    window.setTimeout(logo_blink, (Math.random()*(1500))+1500);
}
logo_blink();

它所做的只是在约30秒内闪烁一次图片(此处的时间较短,以便于调试)

All it makes is blinking a picture once in ~30 seconds (time is less here for easier debugging)

Chrome在背景标签页处于后台时暂停计时器,然后回到该标签页时,它会闪烁所有在后台丢失的闪烁.

The problem that Chrome pauses this timer while the tab in backgrounded, and then, when coming back to that tab, it blinks all the blinks that were missed in background.

我想在后台暂停计时器,但是我不知道如何.我读过一些相关的文章,但似乎它们描述了相反的问题.有什么方法可以检测标签的背景吗?

I'd like to pause the timer while in background, but I don't know how. I've read some related posts, but it seems that they describe the opposite problem. Is there any way to detect the backgrounding of a tab?

推荐答案

这是一个已知功能.为了节省资源,Chrome不会在没有焦点的情况下更新窗口:)例如,您可以检查窗口是否失去焦点并停止计时器.当窗口处于焦点位置时,重新启动它.例如:

It is a known feature. To conserve the resources Chrome does not update the window without focus :) You could check, for example, that window lost its focus and stop the timer. Start it again when window is in focus. For example:

var timer = null;
var logo = $("#blinking-logo");
function logo_blink() {
    if(timer) clearTimeout('timer');
    logo.fadeOut(10).delay(10)
        .fadeIn(10).delay(20)
            .fadeOut(10).delay(10)
            .fadeIn(10)
    timer = window.setTimeout(logo_blink, (Math.random()*(1500))+1500);
}
logo_blink();
$(window).blur(function(){clearTimeout(timer); timer = null;});
$(window).focus(function(){if (!timer) timer = window.setTimeout(logo_blink, (Math.random()*(1500))+1500);});

类似这样的事情.在我的带有动画的页面上,a的setInterval存在相同的问题,因此我只是在页面处于后台时暂停它.

Something like this. On one of my pages with animation a had the same problem with setInterval, so I just pause it when the page is in background.

if (!$.browser.msie)
{
    $(window).focus(function(){paused = false;});
    $(window).blur(function(){paused = true;});
}

而不是根据暂停标志的值跳过动画.

And than skipped animation based on the value of paused flag.

ps:使用以下讨论的优化来更新代码.

ps: Code is updated with optimization discussed below.

这篇关于递归setTimeout()在后台暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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