简体   繁体   中英

How to make jQuery each loop repeat infinite number of times

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();

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.

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-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM