JQuery: using time delay in each iterator?

I am trying to create a carousel effect that automatically cycles through each photo every 3 seconds.

$(".headline_img").each(function(intIndex){ setTimeout($(this).show(),3000); }); 

Timeout delay does not work.

Shows all images as soon as dom is loaded. This is like ignoring the setTimeout function.

Did I miss something?

Note: I call this using $ (document) .ready, do you think this could affect this?

+4
source share
3 answers

The setTimeout function accepts a reference to a function or string. Your code calls the show method for each item immediately. I'm not sure if this will work:

 $(function () { var t = 3000, $debug = $('#result'); $(".headline_img").each(function(){ var $img = $(this); setTimeout($img.show.bind($img), t); t += 3000; }); }); 
 .headline_img { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="headline_img">One</div> <div class="headline_img">Two</div> <div class="headline_img">Three</div> 

but worth a try ...

+5
source

You need to change the timeout for each of them. Right now, you are simultaneously using the same timeout for all of them. Something like this should work without changing your code:

 $(".headline_img").each(function(intIndex){ setTimeout($(this).show(),3000 * (intIndex +1)); }); 

Refactoring to use a queue can be more reliable in the long run.

+2
source

Or you can use the jQuery delay function.

 $(".headline_img").each(function(intIndex){ $(this).delay(3 * (intIndex + 1)).show(); }); 
0
source

All Articles