Help with the use of JS delay or setTimeout

1

I'm trying to create a loop function that keeps switching between 2 divs. But the result is that when the function restarts, I can not get it to wait again for the 5 second interval of the toggle, causing a wrong visual result.

Follow the function:

$(document).ready(function(){
        ciclos();
        function ciclos(){
            $(".slide:first-child").fadeIn(1000).delay(5000).fadeOut(1000);
            $(".slide:nth-child(2)").delay(6000).fadeIn(1000).delay(5000).fadeOut(1000);
            setTimeout(ciclos, 5000);
        }
    })
    
asked by anonymous 09.09.2017 / 03:14

1 answer

5

If you want two animations on different elements to be made in sequence, you must call one in the completing function of the other.

If we have the animation fadeIn of a <p> and we want after doing a fadeIn in a <h1> we would have to do fadeIn of <h1> in the callback (function that runs when the animation is complete) of fadeIn of <p> , like this:

$("p").fadeIn(1000, function(){ //quando o fadeIn do p termina executa esta função
     $("h1").fadeIn(1000);
});

Transposing this logic to your example would have to change it to look like this:

function ciclos(){
   $(".slide:first-child").fadeIn(1000).delay(5000).fadeOut(1000, function(){
      //esta segunda animação agora é apenas chamada quando a primeira termina
      $(".slide:nth-child(2)").delay(6000).fadeIn(1000).delay(5000).fadeOut(1000, function(){
          //o timeout é agora só chamado quando a segunda animação termina
          setTimeout(ciclos, 5000);
      });
   });
}

Example working (I reduced the times to be easier to see that it works):

$(document).ready(function(){
        ciclos();
        function ciclos(){
            $(".slide:first-child").fadeIn(1000).delay(2000).fadeOut(1000, function(){
              $(".slide:nth-child(2)").
              delay(1000).fadeIn(1000).delay(3000).fadeOut(1000, function(){
                setTimeout(ciclos, 4000);
              });
            });
            
            
        }
    })
.slide { 
  width:300px;
  height:200px;
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><imgclass="slide" src="https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg"><imgclass="slide" src="https://c2.staticflickr.com/4/3899/14383431886_8f0675cf95_b.jpg">
</div>
    
09.09.2017 / 03:42