jQuery setInterval太快,当选项卡是不活跃的

jQuery setInterval too fast when tab is inactive

本文关键字:活跃 选项 setInterval 太快 jQuery      更新时间:2023-09-26

当我的网站处于非活动状态时,我的幻灯片开始切换图片太快,把整个事情搞砸了。

有办法我可以解决这个问题吗?

var img_src = ["1.png", "2.png", "3.png", "4.png"];
var delay = 8000;
var first_run = true;
function switch_pic(position){
  $("#show").attr("src", img_src[position]).fadeOut(0).fadeIn(4000).fadeOut(4000);
}
$(document).ready(function(){
  var i = 0;
  if(first_run){
    switch_pic(i);
    first_run = false;
    i++;
  }
  window.setInterval(function(){
    switch_pic(i);
    delay += 8000;
    i++;
    if(i > 3){   
      i = 0;
      window.clearInterval();
    }
  }, delay);
});

可以这样包装代码:

$(document).ready(function(){
    $([window, document]).focusin(function(){
       //code run when tab is selected
    }).focusin(function(){
       //code to stop all animation
    });
});

这只会让幻灯片运行时,用户正在查看您的网站。

我不知道为什么事情会加速。通常情况下,背景选项卡上的计时器会减慢到至少一秒,但这应该不会影响您的场景。我建议使用console.log()跟踪对函数的调用。

同样,你可以简化你的主循环:

$(document).ready(function(){
  var i = 0;
  window.setInterval(function(){
    switch_pic(i++); // increase i after call
    if(i > 3) i = 0; // reset i
  }, 8000);
});

我认为jQuery的实际版本应该是这样的:

    var intervalId;
    $([window, document]).on('focusin', function(){
        intervalId = setInterval(function() {
            // Action in interval
        }, 3000);
    }).on('focusout', function(){
        if (intervalId) {
            clearInterval(intervalId);
        }
    });

请记住,第一次你的'focusin'没有触发当页面加载,所以你应该使用这个结构:

intervalFunction();
$([window, document]).on('focusin', function(){
    if (!intervalId){
        intervalFunction();
    }
}).on('focusout', function(){
    if (intervalId) {
        clearInterval(intervalId);
        intervalId = undefined;
    }
});
function intervalFunction() {
    // Your function hire
}