简体   繁体   English

使用setInterval()函数闪烁图像

[英]Image flickering with setInterval() function

I have made a carousel and using javascript setInterval() function for rotate image with fixed interval in carousel. 我做了一个轮播,并使用javascript setInterval()函数在轮播中以固定间隔旋转图像。 Here's the script that i had used 这是我使用的脚本

var timeOut = 4000;

function showSlide() {
       //....script for showing image
}

function pauseSlide() {

   setInterval(function(){showSlide();}, timeOut);

}

jQuery(document).ready(function() {
        pauseSlide();
});

Now the problem is when i have change the browser tab and after few minute back again to carousel browser and what i seen carousel running too faster rather than default time interval, images going to change fast suppose 0 time interval. 现在的问题是,当我更改了浏览器选项卡,并在几分钟后再次返回轮播浏览器时,我看到轮播运行得比默认时间间隔快,而不是默认时间间隔,因此要快速更改的图像假定时间间隔为0。 Please help me how can i sort out this. 请帮我如何解决这个问题。

You must get rid of the first interval before starting another, or you start getting more than one interval working simultaneously (ie why you start seeing it go "faster") 您必须先消除第一个间隔,然后再开始另一个间隔,或者开始同时运行多个间隔(即为什么开始看到它“更快”)

Do this 做这个

var timeOut = 4000;
var interval = 0;

function showSlide() {
       //....script for showing image
}

function pauseSlide() {

   clearInterval(interval);
   interval =  setInterval(function(){showSlide();}, timeOut);

}

jQuery(document).ready(function() {
    //NOW you can do multiple pauseSlide() calls
     pauseSlide();
     pauseSlide();
     pauseSlide();
     pauseSlide();
     pauseSlide();
});

From what I know in newer versions of both firefox and chrome, background tabs have setTimeout and setInterval clamped to 1000ms to improve performance. 据我所知,在新版本的Firefox和chrome中,背景标签将setTimeout和setInterval固定为1000ms以提高性能。 So I think that your issue might relate to that. 因此,我认为您的问题可能与此有关。

Maybe this will help : How can I make setInterval also work when a tab is inactive in Chrome? 也许这会有所帮助: 当Chrome中的标签页处于非活动状态时,如何使setInterval也能正常工作?

Image changing faster than expected may indicate that you have more than one call to pauseSlide(), in one way or another. 图像变化快于预期可能表明您以一种或另一种方式调用了pauseSlide()。

Is document ready the only place you call the function ? document ready调用函数的唯一地方吗? Any code in showslide or anywhere triggering a document ready event ? showslide中的任何代码或任何触发文档就绪事件的代码? If you put an alert() in pauseSlide() , does it popup more than once ? 如果将alert()放在pauseSlide() ,它是否会弹出不止一次?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM