Chrome动画超时问题 [英] Chrome timeout problem with animation
问题描述
我使用autplay在jQuery中编写了一个简单的Slider。如果启用了自动播放功能,则设置setTimeout指向一个功能。这个函数然后有一个递归的setTimeout自身。
I've written a simple Slider in jQuery with autplay. If autoplay is enabled a setTimeout is set that points to a function. This function then has a recursive setTimeout to itself.
除Chrome以外,所有的工作都很好。在我更换了一个标签后,等待一段时间然后再回来,滑块就吓坏了。它看起来像有多个活动超时实例...但是,由于我将超时指定给同一个变量,因此不能这样。
All works well, except in Chrome. After I've changed a tab, wait for a while and return, the slider is freaking out. It looks like there are multiple instances of the timeout active... but that cannot be the case since I appoint the timeout to the same variable.
一些相关的代码:
var timer;
function autoplay() {
currentPosition++;
if(currentPosition == numberOfSlides) {
// last slide
currentPosition = 0;
}
manageNavigation(currentPosition);
// Hide / show controls
manageControls(currentPosition);
// animate the slides
slideshowAnimate();
// set timer
if(autoplay_enable) {
//clearTimeout(timer);
timer = setTimeout(function() { autoplay() }, interval*1000)
}
}
function setTimer() {
if(autoplay_enable) {
timer = setTimeout(function() { autoplay() }, interval*1000)
}
}
setTimer();
推荐答案
不,重置定时器
不会取消当前定时器。为此,您需要 clearTimeout
。所有定时器暂存是对定时器的数字引用,而不是闭包或任何此类性质。
No, resetting the value of timer
will not cancel the current timer. For that you need to clearTimeout
. All timer holds is a numeric reference to the timer, not a closure or anything of that nature.
假设您有一个很好的条件来启动 setTimer ()
,你的代码应该看起来更像这样:
Assuming you have a good condition to start setTimer()
, your code should look more like this:
var timer;
function autoplay() {
clearTimeout(timer); //! New code.
currentPosition++;
if(currentPosition == numberOfSlides) {
// last slide
currentPosition = 0;
}
manageNavigation(currentPosition);
// Hide / show controls
manageControls(currentPosition);
// animate the slides
slideshowAnimate();
// set timer
setTimer(); //! Switched from having multiple startup locations.
}
function setTimer() {
if(autoplay_enable) {
timer = setTimeout(autoplay, interval*1000); //! Removed unnecessary closure.
}
}
setTimer();
这篇关于Chrome动画超时问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!