var startIndex = 0;
var data = [1, 2, 3];
var timeout = 1000;
function functionToRun(i, length) {
alert(data[i]);
}
(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);
丹尼尔·瓦萨洛(Daniel Vassallo)答案的修改版,其中将变量提取到参数中,以使函数更可重用:
首先让我们定义一些基本变量:
var startIndex = 0;
var data = [1, 2, 3];
var timeout = 3000;
接下来,您应该定义要运行的功能。如果需要,将通过i,循环的当前索引和循环的长度:
function functionToRun(i, length) {
alert(data[i]);
}
自执行版本
(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