2013-02-28 67 views
0

当我的网站打开的标签处于非活动状态时,我的幻灯片显示开始切换图片的速度过快,并且弄乱了整个事情。当标签处于非活动状态时,jQuery setInterval速度太快

有没有办法解决这个问题?

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); 
}); 
+0

特殊照顾已经使用jQuery。只需使用[jQuery Cycle或Cycle lite](http://jquery.malsup.com/cycle/);没有必要在这里重新发明轮子。 – prodigitalson 2013-02-28 18:27:08

+0

它看起来很有希望,我会看看它。谢谢 – user1867717 2013-02-28 18:32:13

+0

是的它就像一个魅力。 TYVM – user1867717 2013-02-28 18:57:15

回答

0

我包的代码在此:

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

这只会让幻灯片运行,当用户正在浏览您的网站。

+0

他是否需要在'focusout'上绑定某种“停止”? – prodigitalson 2013-02-28 18:32:32

+0

它不起作用,它比现在快5倍。 – user1867717 2013-02-28 18:35:07

+0

@prodigitalson好点...编辑。 – 2013-02-28 18:38:29

0

我不知道为什么事情加快。通常,背景选项卡上的计时器将放慢至少一秒,但这不会影响您的方案。我建议使用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); 
}); 
相关问题