2013-05-01 49 views
4

我只是想在jQuery每個循環的每次迭代後添加一個暫停,我似乎無法弄清楚。jQuery中的等待/暫停/休眠迭代之間的每個循環

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

這不點火每1/2秒,但在一次,而觸發點擊的所有項目。

我想是這樣的(僞):

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

的這種任何的工作方法?

回答

2

你好試試這個,或者你可以寫你的,你已經嘗試了setTimeout函數

演示=>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

你讀幾來源:

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

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

希望它可以幫助:)

示例代碼:

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

你不能真正做到這一點與$.each。您可以使用setTimeout並保留對當前索引的引用:

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); 
+0

+ 1給你! – 2013-05-01 22:27:03

相關問題