使用 setInterval 时,如果我在 Chrome 中切换标签并返回,滑块会疯狂追赶

2022-01-24 00:00:00 google-chrome slider jquery javascript

我的网站上有一个 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.

相关文章