arjs
arjs

Reputation: 2875

How can I make this a better recursive animated jQuery script?

The idea is to animate a cloud div and to have it animate back and forth horizontally in perpetuity. This works, but unfortunately I think it's prone to memory leaks and UI lag. Any advice would be appreciate, thanks.

function animateCloud() {
    $('#cloud').animate({ right: '+=500' }, { duration: 35000, easing: "linear", queue: true });
    animateOpposite();
}

function animateOpposite() {
    $('#cloud').animate({ right: '-=500' }, { duration: 35000, easing: "linear", queue: true });
    animateCloud();
}

$(document).ready(function() {
    animateCloud();
});

Upvotes: 4

Views: 2819

Answers (2)

jAndy
jAndy

Reputation: 235982

I don't think that your code leaks memory at all, but you can create the call shorter.

function animateCloud() {
    $('#cloud').animate({ right: '+=500' }, { duration: 35000, easing: "linear" })
               .animate({ right: '-=500' }, { duration: 35000, easing: "linear", complete: animateCloud });
}

example: http://www.jsfiddle.net/bh3f4/

Upvotes: 4

goat
goat

Reputation: 31813

http://api.jquery.com/animate/

Use the optional callback argument. When an animation finishes, jquery will call your function. Perfect time to animate other direction.

Upvotes: 1

Related Questions