Wait/Pause/Sleep in jQuery Each Loop between Iterations

匿名 (未验证) 提交于 2019-12-03 01:38:01

问题:

I simply want to add a pause after each iteration of a jQuery each loop, I can't seem to figure it out.

$(".item").each(function(i){     var el = this;     var timer = setTimeout(function(){         $(el).trigger("click");     }, 500); }); 

This is not firing every 1/2 second, but rather triggering click on all items at once.

I want something like this (pseudocode):

$(".item").each(function(i){     $(this).trigger("click");     wait(500); // wait a half second before the next iteration }); 

Any working method of this?

回答1:

You cannot really do this with $.each. You can use setTimeout and keep a reference to the index you are currently at:

function process(elements, cb, timeout) {     var i = 0;     var l = elements.length;      (function fn() {         cb.call(elements[i++]);         if (i < l) {             setTimeout(fn, timeout);         }     }()); }  process($('.item'), function() {     $(this).click(); }, 500); 


回答2:

Hiya try this or you can write your a SetTimeOUt function which you already tried

Demo => http://jsfiddle.net/Yq2SL/2/ you will see different parent of div with class=item

API: http://api.jquery.com/jQuery.dequeue/ & http://api.jquery.com/jQuery.queue/#jQuery-queue1

Few sources for your read:

http://forum.jquery.com/topic/delay-and-click-issue

http://blog.project-sierra.de/archives/1559

Hope it helps :)

Sample code:

$(".item").delay(500).queue(function(){    $(this).trigger("click");    $(this).dequeue();  }); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!