javascript + jquery + setinterval + animation

霸气de小男生 提交于 2020-01-02 06:28:54

问题


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

回答1:


Newer versions of jQuery use requestAnimationFrame callbacks to handle effects, and browsers don't process those on hidden tabs.

In the meantime, your setInterval events are still happening, causing more animations to get queued up.

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

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.



来源:https://stackoverflow.com/questions/10671284/javascript-jquery-setinterval-animation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!