Search code examples
jqueryjquery-animatedelay

Delay between animations


I'm trying to add a delay at the beginning of each set of animations. The animation works fine but when I add .delay(5000) before .animate nothing works.

    $(document).ready(function(){

    -->add .delay here <---

    $("#hand").animate({left:'-=300px'},1500 );
    $("#hand").animate({left:'+=300px'},1000 );

    -->add .delay here <---

    $("#hand").animate({left:'-=300px'},1500  );
    $("#hand").animate({left:'+=300px'},1000 );

    $("#hand").animate({left:'-=300px'},1500  );
    $("#hand").animate({left:'+=300px'},1000 );

    });

Is there one set code to use for the same function here? I need it to animate infinitely.


Solution

  • You have to can use chaining for the animation / delay calls - example:

    $("#hand").animate({left:'-=300px'},1500)
              .delay(5000)
              .animate({left:'+=300px'},1500);
    

    Note that the animate() call itself is non-blocking so you have to accommodate for that in the delay() call or move the code to the completion handler instead. See this working JSFiddle example.

    To make this run "forever" you can just wrap it into setInterval():

    setInterval(function() {
        $("#hand").animate({ left: '-=300px'}, 1500)
                  .delay(5000)
                  .animate({left: '+=300px'}, 1000);
    }, 10000);