Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery repeat animation

Tags:

jquery

This code seems to break the remainder of my code?

function sam() {
    $("#animate").children("#box")
        .animate({
        left: '+=1100'},8000, 'linear', function() {
            $("#animate").children("#box").css("left", "0");
            sam();
        });
}

setInterval(sam());

Sorry about the short response but I kept getting blocked by a stupid quality message

like image 298
Samuel Luke Anthony Avatar asked Feb 22 '26 04:02

Samuel Luke Anthony


2 Answers

Try to change

setInterval(sam());

to

setInterval(function(){
    sam()
}, 1000);

which will trigger sam() every second.Your usage of setInterval is wrong

Also, delete sam() call in sam() function.

So final code:

function sam() {
    $("#animate").children("#box")
        .animate({
        left: '+=1100'},8000, 'linear', function() {
            $("#animate").children("#box").css("left", "0");
        });
}

setInterval(function(){
    sam()
}, 1000);
like image 105
genesis Avatar answered Feb 23 '26 18:02

genesis


setInterval needs a second parameter for how often you are going to run the code sam(). but I dont know if you want that, it seems to do that anyway.

function sam() {
    $("#animate").children("#box")
        .animate({
            left: '+=1100'},8000, 'linear', function() {
            $("#animate").children("#box").css("left", "0");
            sam();
        });
}

sam();

should be enought if you want to repeat the animation over and over again, or use setTimeout instead of setInterval.

Set interval will relaunch the code, even if the first run isnt finished, your animation takes 8 seconds, if you say run sam() every 2 second for example you will get a very, very bad result because the codes takes more then 2 seconds to run and you also said that it should rerun itself. I would not use setInterval at all.

Demo: http://jsfiddle.net/voigtan/tG7Gm/2/

like image 27
voigtan Avatar answered Feb 23 '26 17:02

voigtan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!