Maulik Maulik - 1 month ago 10
Javascript Question

Can we auto pause animate() and resume() in setInterval function?

I am trying to give Jquery image animation using

.setInterval()
and
.animate()
function in jquery. My code as follows:

$(document).ready(function(){
setInterval(function(){
$("#animate1").fadeIn('slow').animate({'margin-left':'220px','margin-bottom':'20px'},2000,function(){
$('.1st').animate({'opacity':'0'},1000,function(){$('.1st').animate({'opacity':'1'}) })
}).fadeOut();
$("#animate1").fadeIn('slow').animate({'margin-bottom':'0px','margin-left':'-140px'},2000).fadeOut('slow');
},2000);
});


Now, I want to give animation in
$("#animate2")
but before it start I want that
$("#aniamte1")
to be stop or pause. So, catch is after
$("#animate1")
, I want that to stop/pause and run
$("#animate2")
and again after finish my
$("#animate2")
I want to pause/stop and run
$("#animate1")
. how can we done that??

Answer

You can set a variable when your animation finished. As an example taken from the jQuery documentation (please format your code next time, it's hard to read):

$(document).ready(function(){
   var runAnimate1 = true;
   var runAnimate2 = false; 
   setInterval(function(){ 
      if(runAnimate1) {
        $( "#animate1").animate({
          width: [ "toggle", "swing" ],
          height: [ "toggle", "swing" ],
          opacity: "toggle"
        }, 5000, "linear", function() {
          runAnimate1 = false;
          runAnimate2 = true;
        });
      }

      if(runAnimate2) {
        $( "#animate2").animate({
         width: [ "toggle", "swing" ],
         height: [ "toggle", "swing" ],
         opacity: "toggle"
        }, 5000, "linear", function() {
          runAnimate1 = true;
          runAnimate2 = false;
       });
     }
   });
});

Something like that should work. Consider it as pseudo code, I haven't tested it but you should get the idea. You just need to adopt your animations and you should be fine.