我现在有一个Javascript forEach()循环,但是我需要修改我的代码,以便每500次迭代添加一个“睡眠”。
这个模式允许我每次迭代睡眠3秒:
How do I add a delay in a JavaScript loop?
for (let i=1; i<10; i++) {
setTimeout( function timer(){
alert("hello world");
}, i*3000 );
}在每第2次或每500次迭代中,我如何睡眠?
PS:
解决方案需要运行在Chrome和IE11上。
发布于 2018-09-02 02:38:02
您可以创建一个函数,该函数捕获闭包中的循环变量,并使用返回批处理大小的循环返回一个简单函数。其效果是,它允许您继续您停止的for循环。如果让它返回一个布尔值,指示它是否已经完成,则可以将整个过程包装在一个setInterval中。显示比解释容易:
function batch(batch_size, end){
var i = 0 // capture i in closure
return function(){
for(i; i <= end; i++){
console.log("doing something", i) // work goes here
if (!((i+1) % batch_size)) return i++
}
return false
}
}
var f = batch(5, 11) // 0 - 11 batched in groups of 5
if (f()){ // start immediately, then setInterval if not finished in one batch.
var interval = setInterval(() => {
f() || clearInterval(interval)
}, 2000 )
}
发布于 2018-09-02 01:43:01
递归超时解决方案:
const processInBatches = (array, limit, processFn, timeout) => {
const batch = array.slice(0, limit);
if(!batch.length) {
return;
}
batch.forEach(processFn);
const rest = array.slice(limit);
setTimeout(() => processInBatches(rest, limit, processFn, timeout), timeout);
}
const array = ['a', 'b', 'c', 'd'];
processInBatches(array, 2, (x) => console.log('processing',x), 1000);https://stackoverflow.com/questions/52133343
复制相似问题