Jquery repeat set inteval when function end

2019-08-18 06:24发布

问题:

In this script I want to show image by number 0,1,2 and repeat each time, the problem it´s the next image show until animation and transition image end.

var n_img_s = 2;
i = 0;

function more_slider() {
  if (i > n_img_s) {
    i = 0;
  }
  jQuery(".img_" + i).show(3000).delay(3000);
  jQuery(".img_" + i).hide(2000).delay(1500);
  i++;
}

setInterval("more_slider()", 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="slider_cover">
  <img src="https://images.pexels.com/photos/6602/food-plate-woman-hand.jpg?auto=compress&cs=tinysrgb&h=350" style="display:none;" class="img_0" />
  <img src="https://images.pexels.com/photos/6602/food-plate-woman-hand.jpg?auto=compress&cs=tinysrgb&h=350" style="display:none;" class="img_1" />
</div>

I need, for example, to show image 0, hide finish and in this moment show next image, but not until finish the other image.

But I don´t know how integrate setInterval in this.

Thanks for the help.

回答1:

//get all the images
var $images = $('#slider_cover img');

//accept in the next image index to show
function more_slider(nextImageIndex) {
  //get the image you should show, using eq()
  //so the element will still be in a jQuery object
  var $nextImage = $images.eq(nextImageIndex);
  
  //show the image, and then do something after the duration ends
  $nextImage.show(3000, function(){
    //hide the image, and then do something after the duration ends
    $nextImage.hide(2000, function(){
      //pass in the incremented index, performing a modulus
      //on it so that if the length is equal to the number
      //of images it will go back to 0
      more_slider(++nextImageIndex % $images.length);
    });
  });
}

//initialize the loop, giving it the first image index to show
more_slider(0);
.img_0 { border: 2px solid red; }
.img_1 { border: 2px solid blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="slider_cover">
  <img src="https://images.pexels.com/photos/6602/food-plate-woman-hand.jpg?auto=compress&cs=tinysrgb&h=350" style="display:none;" class="img_0" />
  <img src="https://images.pexels.com/photos/6602/food-plate-woman-hand.jpg?auto=compress&cs=tinysrgb&h=350" style="display:none;" class="img_1" />
</div>