Home > Blockchain >  Looping through elements with setTimeout
Looping through elements with setTimeout

Time:09-29

I'm trying to loop through divs with a delay in between. It works okay the first couple of times through. But then it just keeps getting faster. I can't figure out what I'm doing. Help me stackoverflow, you're my only hope.

showSlides();

function showSlides() {
  $('.mySlides:not(:first)').hide(); 
  $.map($('.mySlides'),function(el){
    myTimeout=setTimeout(function(){
      console.log(el); 
      
      $(el).siblings().fadeOut(1000); 
      $(el).fadeIn(1000); 
      if($(el).is(':last-child')) { clearTimeout(myTimeout); showSlides(); }
    },7000); 
  }); 
}

CodePudding user response:

You are setting timeout for all the slides together almost the same instant. A quick fix is to set in advance the timing in a 7 seconds intervals.

$('.mySlides:not(:first)').hide();

showSlides();

function showSlides() {
  var delay = 2000;
  document.querySelectorAll('.mySlides').forEach(function(el, index) {
    myTimeout = setTimeout(function() {

      $(el).siblings().fadeOut(1000);
      $(el).fadeIn(1000);
      if ($(el).is(':last-child')) {
        clearTimeout(myTimeout);
        setTimeout(showSlides, delay);
      }
    }, delay * (index));
  });
}
.mySlides {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  text-align: center;
  font-size: 128px;
  line-height: 200px;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
</div>

CodePudding user response:

No need for each, map or interval, just use delay and jQuery will loop for you

const $slides = $('.mySlides');

const fadeInAndOut = $el => {
  $el.fadeIn(1000).delay(2000).fadeOut(1000, () => {
    if ($el.next().length) fadeInAndOut($el.next()); // is there a next?
    else fadeInAndOut($el.siblings(':first')); // else start over
  });
};
$slides.hide();
fadeInAndOut($slides.eq(0))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div >
  <div >Slide 1</div>
  <div >Slide 2</div>
  <div >Slide 3</div>
</div>

CodePudding user response:

Here is another take on it:

const $sl=$('.mySlides').hide();
$sl.i=0; $sl.eq(0).show();

setInterval(()=>{
 $sl.eq($sl.i).fadeOut(1000);
 $sl.eq($sl.i=($sl.i 1)%$sl.length).fadeIn(1000);
},2000);
.mySlides {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  text-align: center;
  font-size: 128px;
  line-height: 200px;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
</div>

  • Related