3

I've just created a simple, continuous bounce effect in jQuery but I feel the code isn't all that optimized and am looking 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've done is basically created an animation that adds +10 to the top coordinate of the element, and as a callback function, I'm subtracting 10 from the top coordinate..

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

Furthermore, I want to stop the animation on mouseenter, and have it continue on mouseleave.

stop(true, true) didn't work, neither did dequeue() so I've resorted to turning all animation effects off using jQuery.fx.off = true (stupid, no?)

I'd appreciate any feedback on how this can be optimized.

Here's a jsFiddle.

EDIT: I've just realized that jQuery has started throwing too much recursion errors when disabling and re-enabling the effects.

Thanks in advance,

Marko

Marko
  • 71,361
  • 28
  • 124
  • 158
  • I guess, by calling bounce() within itself as callback, generates a large stack trace and thus results in a too much recursion error. – softcr Aug 31 '10 at 20:12
  • The problem with too much recursion is that there is too much recursion. – Neil N Aug 31 '10 at 20:26
  • Yes @Neil - and in order to understand recursion, you must first understand recursion. – Marko Aug 31 '10 at 20:59

2 Answers2

7

Please try the below code Demo : 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();
    });
});

Edit : I guess in your code multiple CallBack functions are the reason for too much recursion

0

Not much of an improvement but here's my attempt:

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

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

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

Marko Dumic
  • 9,848
  • 4
  • 29
  • 33
  • At first I thought of writing the same code, But it resulted in too much recursion, callBack function is the reason for too much recursion :( –  Aug 31 '10 at 20:24