setTimeout函数意外的行为
问题描述:
我有以下代码来追加批量大小为10的元素数组中的iframe,每个批次的时间间隔为10秒。批处理是一个数组,它有一个JSON对象,每个批处理都有开始和结束索引。追加功能将带有代码的iframe附加到DOM。setTimeout函数意外的行为
当前行为: JS等待10秒钟,并一起追加所有iframe,同时调用追加函数,而不用等待每批10秒。
预期行为: JS在追加每个批处理或每个追加函数调用之前等待10秒钟。
batches.forEach(function (x) {
setTimeout(function() {
append(x, elements);
console.log('appending'+x);
}, 10000);
});
任何想法为什么会发生这种情况?
答
setTimeout
所以你的代码是
setTimeout(..., 10000)
setTimeout(..., 10000)
setTimeout(..., 10000)
// etc
相当于每个超时通话被设置为大致执行的同时,从现在开始10秒不会暂停执行。
你将不得不在每次迭代中增加超时。事情是这样的......
batches.forEach((x, i) => { // where "i" is the current, zero-based index
setTimeout(() => {
// etc
}, 10000 * (i + 1))
})
答
你可以创建一个函数来处理这样的批次:
function processBatch(batches, delay){
setTimeout(function(){
// get the first element/child in batches
var batch = batches[0];
// process your batch the way you want it
console.log(batch);
// remove the already processed batch
batches.splice(0, 1);
if (batches.length > 0){
// process the remainder batches
processBatch(batches, delay)
} else {
console.log('done');
}
}, delay)
}
调用它:
var batches = [1, 2, 3, 4];
processBatch(batches, 100000);
看到它在行动:https://jsfiddle.net/pa64vqxr/ (别忘了打开浏览器控制台)
相关:https://stackoverflow.com/q/45767325/5894241 – Nisarg
你的foreach循环只是遍历所有元素而不停止。所以它会很快为每个元素创建一个setTimeout。然后他们等待10秒钟,然后立刻执行所有操作。如果你希望他们在不同的时间执行,那么你必须给他们每个不同的延迟。 – RJM