JavaScript 中的 setTimeout
我正在使用以下代码对 javascript 中的某个过程进行动画处理:
var direction = $('#rightControl');
function animate()
{
if (hover) return;
if (!direction.is(':visible'))
{
if (direction.attr('id') == 'rightControl') direction = $('#leftControl');
else direction = $('#rightControl');
}
doMove(direction);
}
// Animate slider!
setInterval(animate, 2500);
直到元素 #rightControl
存在于页面:每 2.5 秒调用 animate()
函数并移动我的 div(在 >doMove
)。当 #rightControl
消失时,我将方向更改为 #leftControl
,...
一切都很好,但是当页面在后台运行一段时间(例如,4-5 分钟) ),动画变得疯狂,每次调用100-200毫秒。怎么了?
I'm animating some process in javascript with this code:
var direction = $('#rightControl');
function animate()
{
if (hover) return;
if (!direction.is(':visible'))
{
if (direction.attr('id') == 'rightControl') direction = $('#leftControl');
else direction = $('#rightControl');
}
doMove(direction);
}
// Animate slider!
setInterval(animate, 2500);
Until element #rightControl
exists at page: call animate()
function each 2.5 seconds and move my div (inside doMove
). When the #rightControl
dissappears I change direction into #leftControl
, ...
Everything works cool, but when page is in background a few time (for example, 4-5 minutes), the animation becomes crazy and call each 100-200 ms. What's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,setInterval 只是每隔 * 秒向调用堆栈添加一些内容。如果某些 JavaScript 执行了几秒钟,调用堆栈上可能会出现一些情况。我猜如果页面也在后台,这种情况也可能发生。检查它是否与 setTimeouts 一起使用(因此 1 或函数调用来启动它,1 在函数末尾)。
Hmm, setInterval just adds something to the call-stack every * seconds. If there is some javascript being executed for a few seconds, things might build up on the call stack. That could happen if the page is in background too I guess. Check if it works with setTimeouts (so 1 or a function call to start it, 1 at the end of the function).
我可以猜测的是,要么
setInterval()
在别处被意外调用,要么animate()
被意外调用。试试这个小提琴: http://jsfiddle.net/fXJbW/
仅使用
animate()
和setInterval()
即可正常工作。问题出在你的代码的其余部分。您可以做的另一件事是:
What I can guess is that either
setInterval()
is accidentally being called elsewhere, oranimate()
is.Try this fiddle: http://jsfiddle.net/fXJbW/
It works fine with just
animate()
andsetInterval()
. The problem is in the rest of your code.Another thing you can do is this: