首页 > 解决方案 > for-loop 中的 Discord.js setTimeout 正在同时打印值,有没有办法让这个简单的程序工作

问题描述

我的代码是:

for (let i = 0; i <= 5; i++) {
  delay(i);
}

function delay(i) {
  setTimeout(() => console.log(`${i} is the number`), 2000);
}

我在 2 秒后得到的输出是:

0 是数字

1 是数字

2 是数字

3是数字

4是数字

5是数字

它们都在 2 秒后立即打印在一起,而我希望它们每个都在 2 秒后打印,例如:

0 是数字

(2秒后)

1 是数字

(2秒后)

2是数字.....

有什么办法让它工作吗?谢谢!!

标签: javascriptfor-loopdiscord.jssettimeout

解决方案


setTimeout是一个非阻塞函数。for循环不等待完成,delay而是delay(i)直接连续调用六次。

为了使这种情况有效,您可以使用async/awaitPromise-ify setTimeout

(async () => {
for (let i = 0; i <= 5; i++) {
    await delay(i);
}
})();

function delay(i) {
return new Promise(resolve => setTimeout(() => {
    console.log(`${i} is the number`);
    resolve();
}, 2000));
}


推荐阅读