我有这段 Javascript 代码。
var headlineStore = [
function headline1(){
//irrelevant code
},
function headline2(){
//irrelevant code
},
function headline4(){
//irrelevant code
},
function headline4(){
//irrelevant code
},
function headline5(){
//irrelevant code
}
]
for(var i = 0; i < headlineStore.length; i++){ //for loop to loop through array named headlineStore
if(i == 4) //if condition to reset the counter once it reaches 5
{
i = 0;
}
(function(i){
setTimeout(function(){
headlineStore[i]();
}, 5000 * i);
}(i)); //Will load each function in the array with timeout increments
}
我这里有一个 for 循环,它循环遍历一个充满函数的数组。在每次迭代中,都会检索数组中的一个函数并按时间间隔执行。
我想要的是,在检索到最后一个函数后,它从第一个函数开始再次循环遍历数组,并将无限循环。
我尝试的是在计数器达到 4 时重置计数器,但它跳出循环并继续执行,然后由于某种原因页面变得无响应。
最佳答案
您需要等到最后一个执行后才能设置下一个超时时间:
var headlineStore = [
function headline1(){
document.write('1');
},
function headline2(){
document.write('2');
},
function headline3(){
document.write('3');
},
function headline4(){
document.write('4');
},
function headline5(){
document.write('5');
}
]
function nextHeadline(index) {
headlineStore[index]();
window.setTimeout(
nextHeadline.bind(undefined, (index + 1) % headlineStore.length), 1000 );
}
nextHeadline(0);
关于Javascript 无限循环遍历数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36630950/