简体   繁体   English

javascript + jquery + setinterval + animation

[英]javascript + jquery + setinterval + animation

I'm having a problem with setInterval and jquery animate. 我遇到了setInterval和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);
});

Newer versions of jQuery use requestAnimationFrame callbacks to handle effects, and browsers don't process those on hidden tabs. 较新版本的jQuery使用 requestAnimationFrame回调来处理效果,浏览器不会处理隐藏选项卡上的那些。

\n

In the meantime, your setInterval events are still happening, causing more animations to get queued up. 与此同时,您的 setInterval事件仍在发生,导致更多动画排队等候。

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. 不使用setInterval来调度动画,而是使用上一个动画的“完成回调”来触发下一个循环,必要时使用setTimeout

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()"
});

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. 这将确保在交感延迟和动画本身之间存在紧密耦合,并避免setTimeout与动画不同步的任何问题。

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

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