我有这个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时重置,但是它退出循环并继续执行,然后由于某种原因页面变得没有响应。
发布于 2016-04-14 10:43:37
在设置下一个超时之前,您需要等到最后一个执行:
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);
发布于 2016-04-14 10:42:28
我认为这更符合您需要的内容(每5秒调用1函数)。对这种使用setTimeout的支持取决于浏览器
var timeoutHandle = undefined;
headlineStore =
[ function1
, function2
, function3
...
];
function showHeadline(idx) {
headlineStore[idx](idx);
timeoutHandle = setTimeout(showHeadline, 5000, (idx+1)%headlineStore.length);
}
showHeadline(0);
发布于 2016-04-14 10:41:44
你可以利用.queue()
,.promise()
var headlineStore = [
function headline1(next) {
//irrelevant code
console.log("headline1");
setTimeout(next, 5000);
},
function headline2(next) {
//irrelevant code
console.log("headline2");
setTimeout(next, 5000);
},
function headline3(next) {
//irrelevant code
console.log("headline3");
setTimeout(next, 5000);
},
function headline4(next) {
//irrelevant code
console.log("headline4");
setTimeout(next, 5000);
},
function headline5(next) {
//irrelevant code
console.log("headline5");
setTimeout(next, 5000);
}
];
(function cycle() {
return $({}).queue("headlines", $.map(headlineStore, function(headline, i) {
return headline
})).dequeue("headlines")
.promise("headlines")
.then(cycle) // loop infinitely
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
https://stackoverflow.com/questions/36630950
复制