Javascript for循环(如何使其永远重复)
我有一个for循环正在工作,但是当完成时,我希望它再次开始并重复这个过程Javascript for循环(如何使其永远重复),javascript,for-loop,Javascript,For Loop,我有一个for循环正在工作,但是当完成时,我希望它再次开始并重复这个过程 for (var i = 0; i != 3; i = i + 1) { (function(index) { setTimeout(function() { document.getElementById(location[index]).style.background = color[index]; }, 1000 * index
for (var i = 0; i != 3; i = i + 1) {
(function(index) {
setTimeout(function() {
document.getElementById(location[index]).style.background = color[index];
}, 1000 * index);
})(i);
}
您可以使用second for循环。在第二个循环中,写下要重复第一个循环多少次。也可以使用while循环。将初始for循环嵌入另一个for循环中,以使循环重复一定的时间 例如(其中number是希望循环重复的
次数):
for(变量i=0;i
您不希望在或时使用任何循环结构,如。相反,只需创建一个被索引调用的函数来启动它,然后在回调中,它增加索引并递归调用同一个函数。当索引到达3
时,在递归调用之前将其设置回0
function cycle(index) {
setTimeout(function() {
document.getElementById(location[index]).style.background = color[index];
index++; // Increment the index
if (index >= 3) {
index = 0; // Set it back to `0` when it reaches `3`
}
cycle(index); // recursively call `cycle()`
//cycle(++index % 3);
}, 1000);
}
cycle(0);
我使用了%
操作符来快速确保在递归调用中将其设置回0
。while
..但是你真正想要的是让它在超时时工作,是一个递归函数将循环嵌入另一个循环我对你的代码有问题,但这不是你的问题。为什么要使用函数(索引)?我看你不需要它。@RockOnGom:他正在做,如果使用setInterval
,那就更有意义了。我认为这种答案不值得成为社区维基。@MarcoBonelli:我的答案都是社区维基的setInterval
会起作用,但我不会说“更有意义”。只有两种不同的方法来做同样的事情。感谢这一切现在都在工作。如果说索引在2,是从循环中断运行一个函数,然后继续循环,有可能吗?谢谢James@coolbotic:为什么需要打破循环?当索引===2
时,你就不能运行这个函数吗?啊,没想到,现在就试试吧,谢谢!我会把它放在循环(0)下;对的
function cycle(index) {
setTimeout(function() {
document.getElementById(location[index]).style.background = color[index];
index++; // Increment the index
if (index >= 3) {
index = 0; // Set it back to `0` when it reaches `3`
}
cycle(index); // recursively call `cycle()`
//cycle(++index % 3);
}, 1000);
}
cycle(0);