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

查看:19
本文介绍了使用 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 在 Chrome 中检测标签何时聚焦或不聚焦?

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

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

适用于您的情况:

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

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

请注意,在最新版本的 Chromium 中,要么存在错误,要么存在降低可靠性的功能",要求用户在窗口中的任意位置至少单击一次.有关详细信息,请参阅上面的链接问题.

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天全站免登陆