简体   繁体   中英

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();
});

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM