我想在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