var startIndex = 0;
Var数据= [1,2,3];
Var超时= 1000;
函数functionToRun(i, length) {
警报(数据[我]);
}
(函数forWithDelay(i, length, fn, delay) {
setTimeout(函数(){
fn(我、长度);
我+ +;
If (i < length) {
forWithDelay(i, length, fn, delay);
}
},延迟);
}) (startIndex数据。length, functionToRun, timeout);
Daniel Vassallo回答的修改版本,将变量提取为参数,使函数更具可重用性:
首先让我们定义一些基本变量:
var startIndex = 0;
var data = [1, 2, 3];
var timeout = 3000;
接下来,您应该定义要运行的函数。这将传递i,循环的当前索引和循环的长度,以防你需要它:
function functionToRun(i, length) {
alert(data[i]);
}
Self-executing版本
(function forWithDelay(i, length, fn, delay) {
setTimeout(function () {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
})(startIndex, data.length, functionToRun, timeout);
功能版
function forWithDelay(i, length, fn, delay) {
setTimeout(function () {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
}
forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it