gpt4 book ai didi

javascript - 如何对 JavaScript 操作进行计时,以便它们按正确的顺序发生

转载 作者:行者123 更新时间:2023-12-01 02:38:37 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何为这个 for 语句计时,以便它每秒左右发生一次。最终发生的情况是,x 为所有日志打印 5,因为 for 循环在超时发生之前循环。如何对循环进行计时,以便每次迭代都在 setTimeout 完成后发生。

for (x = 0; x < 5; x++) {  
var wait = setTimeout( function() {
console.log(x,"x");
}, 800);
}

最佳答案

使用let x = 0确保x在循环中处于 block 作用域,并乘以延迟时间索引以增加每个延迟时间

for (let x = 0; x < 5; x++) {
setTimeout(function() {
console.log(x, " x")
}, (x + 1) * 800);
}

关于javascript - 如何对 JavaScript 操作进行计时,以便它们按正确的顺序发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47719066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com