Improving this continuous jQuery animation
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 ani开发者_Go百科mation 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
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
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;
});
精彩评论