我想在10秒延遲的循環中執行幾行。添加下面的代碼,在jquery中添加循環執行延遲
$(xmlResponse).find("row").each(function()
{
setInterval(
//some set of code here
,10000);
});
我不知道如果我這樣做的權利,可以在任何一個你請指導我?
問候, 阿什溫
我想在10秒延遲的循環中執行幾行。添加下面的代碼,在jquery中添加循環執行延遲
$(xmlResponse).find("row").each(function()
{
setInterval(
//some set of code here
,10000);
});
我不知道如果我這樣做的權利,可以在任何一個你請指導我?
問候, 阿什溫
你可能想的setTimeout(),因爲它只能觸發一次:
$(xmlResponse).find("row").each(function() {
setTimeout(//some set of code here ,10000);
});
現在,很明顯的OP想在.each()
循環執行一個操作,每10秒,有幾種方法可以做到這一點。一種方法是將大量的setTimeout()
調用堆積起來,爲整個循環的日程安排工作。我不喜歡這樣做,因爲它使得很難在未來的工作中做出邏輯決策。相反,我傾向於改變你迭代到像這樣的常用設計模式的方式:
var rows = $(xmlResponse).find("row");
var cntr = 0;
function nextRow() {
if (cntr < rows.length) {
var currentRow = rows.eq(cntr);
// do your operation on currentRow here
++cntr;
// schedule the next row for 10 seconds from now
setTimeout(nextRow, 10 * 1000);
}
}
// start the first one
nextRow();
你是否運行了你的代碼? – worldask 2014-09-19 06:37:28
setInterval將每10秒運行一次,如果您只想運行一次,請將其更改爲setTimeout – worldask 2014-09-19 06:39:08
您不能讓循環的迭代實際上等待或延遲。這不是javascript的工作原理。您可以使用'setTimeout()'來安排將來運行的代碼,但是從您的問題中可以看出,這正是您想要的,或者您只是想慢慢進行迭代,每10秒一個項目。請更詳細地描述你真正想要完成的事情。 – jfriend00 2014-09-19 06:42:10