当使用setInterval时,如果我在Chrome中切换标签并返回,则滑块变得疯狂追赶 [英] When using setInterval, if I switch tabs in Chrome and go back, the slider goes crazy catching up

查看:99
本文介绍了当使用setInterval时,如果我在Chrome中切换标签并返回,则滑块变得疯狂追赶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网站上有一个jQuery滑块,下一张幻灯片的代码位于名为nextImage的函数中。我使用setInterval在计时器上运行我的功能,并且它完全按照我的要求运行:它在计时器上运行我的幻灯片。但是,如果我在Chrome中访问该网站,切换到另一个选项卡并返回,滑块会不断滑过幻灯片,直到它赶上为止。有谁知道一种方法来解决这个问题。以下是我的代码。

I have a jQuery slider on my site and the code going to the next slide is in a function called nextImage. I used setInterval to run my function on a timer, and it does exactly what I want: it runs my slides on a timer. BUT, if I go to the site in Chrome, switch to another tab and return, the slider runs through the slides continuously until it 'catches up'. Does anyone know of a way to fix this. The following is my code.

setInterval(function() {
nextImage();
}, 8000);


推荐答案

>如何检测标签是否集中在铬与JavaScript?

window.addEventListener('focus', function() {
    document.title = 'focused';
},false);

window.addEventListener('blur', function() {
    document.title = 'not focused';
},false);

适用于您的情况:

To apply to your situation:

var autopager;
function startAutopager() {
    autopager = window.setInterval(nextImage, 8000);
}
function stopAutopager() {
    window.clearInterval(autopager);
}

window.addEventListener('focus', startAutopager);    
window.addEventListener('blur', stopAutopager);

请注意,在最新版本的Chromium中,有一个bug或一个特征这使得它不太可靠,要求用户至少在窗口的任何地方点击过一次。有关详细信息,请参阅上面的链接问题。

Note that in the latest version of Chromium, there is either a bug or a 'feature' which is making this less reliable, requiring that the user has clicked at least once anywhere in the window. See linked question above for details.

这篇关于当使用setInterval时,如果我在Chrome中切换标签并返回,则滑块变得疯狂追赶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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