javascript + jquery + setinterval + animation [英] javascript + jquery + setinterval + animation
问题描述
我遇到了setInterval和jquery animate的问题。这是我的代码:
I'm having a problem with setInterval and jquery animate. Here is my code:
function slides1() {
...
$("table#agah1").animate({
"left": first1
}, "slow");
$("table#agah2").animate({
"left": first2
}, "slow");
}
$(function () {
cyc = setInterval("slides1()", 3000);
});
当切换到另一个浏览器标签,并在一段时间后返回时,动画会毫不拖延地继续进行,我已离开标签,然后行动正确。我添加了这些也没有任何运气:
When switch to another browser tab, and return after a time, the animation keep doing it without delay, for the time I've been away from the tab, and then act correct. I've added these also without any luck:
$(window).focus(function () {
jQuery.fx.off = false;
cyc = setInterval("slides1()", 3000);
});
$(window).blur(function () {
jQuery.fx.off = true;
window.clearInterval(cyc);
});
推荐答案
jQuery的新版本使用 requestAnimationFrame
处理效果的回调,浏览器不处理隐藏标签上的那些。
Newer versions of jQuery use requestAnimationFrame
callbacks to handle effects, and browsers don't process those on hidden tabs.
同时,你的 setInterval
事件仍在发生,导致更多动画排队等待。
In the meantime, your setInterval
events are still happening, causing more animations to get queued up.
而不是使用 setInterval
来安排动画,使用上一个动画的完成回调来触发下一个周期,必要时使用 setTimeout
。
Rather than use setInterval
to schedule the animations, use the "completion callback" of the last animation to trigger the next cycle, with a setTimeout
if necessary.
function slides1() {
...
$("table#agah1").animate({
"left": first1
}, "slow");
$("table#agah2").animate({
"left": first2
}, "slow", function() {
setTimeout(slides1, 2000); // start again 2s after this finishes
});
}
$(function () {
setTimeout(slides1, 3000); // nb: not "slides1()"
});
这将确保在动画延迟和动画本身之间存在紧密耦合,并避免任何问题与 setTimeout
与动画不同步。
This will ensure that there's a tight coupling between the interanimation delay and the animations themselves, and avoid any issues with setTimeout
getting out of sync with the animations.
这篇关于javascript + jquery + setinterval + animation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!