fadeIn of divs in a loop?

1

I have the following code that I would like to make fadeIn and fadeOut after 3 seconds. I thought I would use setInterval to loop and then use setTimeout to give the time each div was visible. Is there any way to do what I want? I have something wrong with my code?

setInterval(function(){
    setTimeout(function(){
        $(".emer3").fadeOut("fast");
        $(".emer1").fadeIn("fast");
    }, 3000);

    setTimeout(function(){
        $(".emer1").fadeOut("fast");
        $(".emer2").fadeIn("fast");
    }, 3000);

    setTimeout(function(){
        $(".emer2").fadeOut("fast");
        $(".emer3").fadeIn("fast");
    }, 3000);
}, 9000);



<div class="col-lg-12 col-sm-12 col-xs-12 col-md-12" style="margin-top:100px;">
  <div class="col-lg-4 col-sm-4 col-xs-4 col-md-4 emer1">
    252 252 252
  </div>
  <div class="col-lg-4 col-sm-4 col-xs-4 col-md-4 emer2" style="display:none">
    252 252 252
  </div>
  <div class="col-lg-4 col-sm-4 col-xs-4 col-md-4 emer3" style="display:none">
    252 252 252
  </div>
</div>

Example in this JSFIDDLE

    
asked by anonymous 19.10.2017 / 12:18

1 answer

1

In your code, the problem is that all setTimeout starts at the same time, so the waits end simultaneously.

When you want to chain animations in Jquery, you should use the complete function, which is a callback, like this:

$(".umaclass").fadeIn("fast", function(){
    //aqui vem o código a executar quando esta animação acaba
});

If you do not do this then all fades for different elements run concurrently.

For your concrete problem of animating divs in sequence I suggest another approach, which is even more scalable, by building an array of divs to animate and animate in sequence based on the position in which it goes.

Example:

const divs = [$(".emer1"), $(".emer2"),$(".emer3")]; //divs a animar
let i = 0; //div corrente

function animar(){
  divs[i].fadeOut("fast"); //fadeout do corrente
  i = (i+1>=divs.length)?0:i+1; //descobrir o proximo
  divs[i].fadeIn("fast", function(){ //fadein do proximo
    setTimeout(() => { animar() } ,3000); //esperar 3 segundos e repetir o processo
  });
}

setTimeout(()=>animar(), 3000); //iniciar tudo em 3 segundos
.emer1 {
  background-color:cyan;
}

.emer2 {
  background-color:yellow;
}

.emer3 {
  background-color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="col-lg-12 col-sm-12 col-xs-12 col-md-12" style="margin-top:100px;">
  <div class="col-lg-4 col-sm-4 col-xs-4 col-md-4 emer1">
    252 252 251
  </div>
  <div class="col-lg-4 col-sm-4 col-xs-4 col-md-4 emer2" style="display:none">
    252 252 252
  </div>
  <div class="col-lg-4 col-sm-4 col-xs-4 col-md-4 emer3" style="display:none">
    252 252 253
  </div>
</div>

Documentation for fadeIn and fadeOut

Note: I put some colors in the divs to make the effect more obvious.

    
19.10.2017 / 13:31