开发者

jQuery: Using a Time Delay in an Each Iterator?

I'm trying to create a carousel effect that auto开发者_C百科matically cycles through each pictures every 3 seconds.

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

The timeout delay is not working.

This shows all of the images instantly as soon as the dom loads. It's like its ignoring the setTimeout function.

Did I miss something?

Note: I'm calling this using $(document).ready, do you think that might effect it?


The setTimeout function takes a function reference or a string. Your code calls the show method for each element 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 it's worth a try...


You need to change the timeout for each one. Right now, you're attaching the same timeout to all of them at the same time. Something like this should work without changing your code much:

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

Refactoring to use queue might be more robust in the long term.


Or you can use jQuery's delay function.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜