Improving this continuous jQuery animation

I just created a simple, continuous bounce effect in jQuery, but I feel that the code is not all that optimized, and I look to improve it.

var $square = $("#square");
bounce();
function bounce() {
    $square.animate({
        top: "+=10"
    }, 300, function() {
        $square.animate({
            top: "-=10"
        }, 300, function() {
            bounce();
        })
    });
}

$square.hover(function() {        
    jQuery.fx.off = true;
}, function() {
    jQuery.fx.off = false;
});

All I did was basically create an animation that adds +10 to the top coordinate of the element, and as a callback function, I subtract 10 from the top coordinate.

This creates a (almost smooth) bounce effect, but I feel it can be improved.

In addition, I want to stop the animation on mouseenterand continue it on mouseleave.

stop(true, true)didn't work, didn't dequeue(), so I resorted to disabling all animation effects with jQuery.fx.off = true(stupid, no?)

I would be grateful for any feedback on how this can be optimized.

jsFiddle.

EDIT: , jQuery too much recursion .

,

+3
2

: http://jsfiddle.net/LMXPX/

$(function() {
    var $square = $("#square"),flag = -1;
    var timer = bounce = null;
    (bounce = function () {
        timer = setInterval(function() {
            flag = ~flag + 1;
            $square.animate({ 
                top: "+="+(flag*10)
            }, 300)
        },300);
    })();                
    $square.hover(function() {        
        clearInterval(timer);
    }, function() {
        bounce();
    });
});

: , CallBack

+7

, :

var $square = $("#square");

(function loop () {
    $square
        .animate({ top: "+=10" }, 300)
        .animate({ top: "-=10" }, 300, loop );
})();

$square.hover(function() {
    $.fx.off = !$.fx.off;
});

0

Source: https://habr.com/ru/post/1762518/


All Articles