2

I am trying to create a slideshow and repeat an each loop once it has cycled through each image. I have tried everything but cannot get the loop to continue after it has cycled through each image. Please see my code and attempt below.

Anyone have any ideas? Have tried everything.

html

<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-1.jpg" />
<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg" />
<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-3.jpg" />

js

function test() {
    $("img").each(function(index) {
        $(this).hide();
        $(this).delay(3000 * index).fadeIn(3000).fadeOut();
    });

   if(index === 3){
      index = 0;
   }
}
test();
  • Check out an infinite loop using a while loop: http://stackoverflow.com/questions/24977456/how-do-i-create-an-infinite-loop-in-javascript – numX Jul 24 '16 at 16:07
  • Check out: http://stackoverflow.com/questions/38535176/how-do-i-add-a-cycle-style-repeating-image-phase-background-to-my-website/38535755#38535755 – JonSG Jul 24 '16 at 16:27

2 Answers2

3

You should just start the loop again after the interval, no need to reset the index (which also does completely nothing).

function test() {
    $("img").each(function(index) {
        $(this).hide();
        $(this).delay(3000 * index).fadeIn(3000).fadeOut();
    });
    setTimeout(test,9400)
}
test();

Since there're three imgs, each showing with the delay of 3000, and fadeOut takes 400 ms by default, the delay should be:

3*3000+400 = 9400

Note that every next fadeIn doesn't wait for completion of the previous fadeOut, thus stealing first two 400 ms delays of fadeOut.

nicael
  • 18,550
  • 13
  • 57
  • 90
3

Your best bet is to use the promise:

function test() {
    $("img").hide().each(function(index) {
        $(this).delay(3000 * index).fadeIn(3000).fadeOut();
    }).promise().done(test);
}
test();

-jsFiddle-

A. Wolff
  • 74,033
  • 9
  • 94
  • 155