setTimeout 在我的 for 循环中不起作用 - 完全跳过它
setTimeout not working inside of my for loop - skipping it completely
function whatever () {
for (var i=0; i < arr.length; i++) {
do something
slowDown();
};
};
function slowDown () {
time = setTimeout(function (){
do something else
}, 5000);
};
为什么不直接设置和间隔,对当前数组值执行直到完成,然后清除它?
let ctr = 0, time = setInterval(function() {
let curitem = arr[ctr];
// do somethign with curitem
if (++ctr >= arr.length) clearInterval(time)
}, 5000);
@vlaz 在问题的评论中指出的是正确的:
slowDown() will schedule something to execute later. It will not actually slow down anything. If you have a loop over 10 items, then you'd just have 10 tasks scheduled to execute 5 seconds later.
不确定这是否有帮助,但我认为这很相似
function whatever () {
for (var i=0; i < arr.length; i++) {
do something
slowDown();
};
};
function slowDown () {
time = setTimeout(function (){
do something else
}, 5000);
};
为什么不直接设置和间隔,对当前数组值执行直到完成,然后清除它?
let ctr = 0, time = setInterval(function() {
let curitem = arr[ctr];
// do somethign with curitem
if (++ctr >= arr.length) clearInterval(time)
}, 5000);
@vlaz 在问题的评论中指出的是正确的:
slowDown() will schedule something to execute later. It will not actually slow down anything. If you have a loop over 10 items, then you'd just have 10 tasks scheduled to execute 5 seconds later.
不确定这是否有帮助,但我认为这很相似