Animate () does not work continuously

I want to animate #anicontinuously using animate()in jQuery. My code only works once. How to make this animation loop?

Here is my code and you can see the online demo here .

HTML

<div id="ani">animation</div>

SCRIPT

$('#ani').css('position','absolute');

setTimeout(function(){
    $('#ani').animate({top:'-10px'},2000)
},100);

setTimeout(function(){
    $('#ani').animate({top:'20px'},2000)
},100);
+3
source share
5 answers
$('#ani').css('position','absolute');
function loop(){
    $('#ani').animate({top:'-10px'},2000,function(){
        $('#ani').animate({top:'20px'},2000,function(){
               loop();            
        }) ;                
    })    

}
loop()               

I think you can see a modified online demo: http://jsfiddle.net/9hN2g/5/

+2
source

You need to use setInterval(), and not setTimeout(), call the second part of the animation as a callback to the first. Try the following:

function animate() {
    $('#ani').stop(true, true).animate({ top: '-10px' }, 1000, function() {
        $('#ani').stop(true, true).animate({ top: '20px' }, 1000)
    })
}

animate(); // on load
setInterval(animate, 2000); // set to run continously

Script example

+1
source

:

  • (100ms) 2 , #ani -10px.
  • ( 100ms) 2- , #ani 20px.

jQuery . :

setTimeout(function(){
    $('#ani').animate({top:'-10px'}).animate({top:'20px'}),2000);
},100);

For continuous animation you will need to use callbacks; function to call when the animation ends.

function moveUp() {
   $('#ani').animate({ top: -10 }, 2000, moveDown);
}

function moveDown() {
   $('#ani').animate({ top: 20 }, 2000, moveUp);
}

setTimeout(moveUp, 100);
+1
source

make your functions recursive.

$('#ani').css('position', 'absolute');
anim1();
function anim1() {
    setTimeout(function() {
        $('#ani').animate({
            top: '-10px'
        }, 2000, function(){
            anim2();
        });
    }, 100);
}

function anim2() {
    setTimeout(function() {
        $('#ani').animate({
            top: '20px'
        }, 2000, function(){
            anim1();
        });
    }, 100);
}​


Demo

0
source

see this time http://jsfiddle.net/9hN2g/8/ , just replace the setTimeout () function with setInterval ().

follow this link once to better understand diff b / w these two pleasures http://www.whadiz.com/what-is.aspx/programming/javascript/settimeout-versus-setinterval

$('#ani').css('position','absolute');

setInterval(function(){
    $('#ani').animate({top:'-10px'},2000)
},100);

setInterval(function(){
    $('#ani').animate({top:'20px'},2000)
},100);
0
source

All Articles