Search code examples
jqueryperformancejquery-animateresume

Why does my animation go extremely slow upon resuming?


I have a jQuery animation that animates the 'scrollLeft' on a container to produce a kind of 'marquee' effect.

I have it set up so on mouse-over of the container it stops the animation, and on mouse-leave, it resumes.

$(banksContainer).mouseover(function() {
    $(banksContainer).stop(false);
});

$(banksContainer).mouseleave(function() {
    startAnimation();
});

Whenever I move the mouse over the animation then off the animation, it resumes at an extremely slow speed, but gradually picks up after a minute or so.

Why is this happening and can it be resolved?

PS. Here's the startAnimation function as requested:

// recursive function - represents one cycle of the marquee
function startAnimation() {
    $(banksContainer).animate(
        { scrollLeft: scrollLeftEnd },
        35000,
        "linear",
        function() {
            $(this)[0].scrollLeft = scrollLeftHome;
            startAnimation();
        }
    );
}

Solution

  • That's probably because when you resume the animation, the distance to cover has reduced but the time remains at 35 seconds. since speed = distance / time, it would be slow.

    I think you should set the time proportionate to the distance remaining. That would be 35000 * distance remaining / total distance.

    Something like this?

    function startAnimation() {
        $(banksContainer).animate(
            { scrollLeft: scrollLeftEnd },
            35000 * this.scrollLeft() / scrollLeftEnd, //or scrollLeftHome whichever is non-zero
            "linear",
            function() {
                $(this)[0].scrollLeft = scrollLeftHome;
                startAnimation();
            }
        );
    }