[英]How to use setTimeout in a for loop
我正在discord.js
中构建一个 Minecraft 主题机器人,我写了一个命令,它基本上开始开采资源,然后等待一段时间,因为在现实生活中,在 Minecraft 中开采石头需要一些时间,而且还取决于类型镐。 所以我想做的是,每次你挖出一个块后,它会根据你的镐的速度等待一段时间,然后它会再次运行,为此,我想到了使用setTimeout()
function。 但是我遇到了一个问题。 问题是,当setTimeout()
运行时,它并没有停在那里,而是继续执行setTimeout()
之后的代码,一旦setTimeout()
完成,它就会执行setTimeout()
中的代码。 我已经研究了一段时间如何做到这一点,但它们似乎都不适用于我的想法。 我的代码是这样的 =>
async execute(interaction) { // It gets the pickaxe details const pickaxe = require('../${pickaxeId}.js') // This gets the time to mine stone, coal and iron from the pickaxe file const timeToMineStone = pickaxe.stone const timeToMineCoal = pickaxe.coal const timeToMineIron = pickaxe.iron const minableBlocks = ['stone', 'coal', 'iron'] var miningTime // It picks one block randomly from the minableBlocks and depending on it, it assigns a value to the miningTime variable // Code for picking the random block for (var mined = 0; mined <= 100; mined++) { setTimeout(() => { console.log('Time Out,') }, miningTime) // Rest of the code should only be executed after the setTimeout() } }
但是这里发生的是,在setTimeout()
之后编写的代码的 rest 首先执行,然后在超时后,它会记录“超时”。 到控制台。 谁能帮助我正确使用setTimeout()
吗? 任何帮助,将不胜感激。
您的
sleep
function 不起作用,因为setTimeout
没有(还没有?)返回可以await
的 promise 。 您将需要手动承诺它:
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function sleep(fn, ...args) {
await timeout(3000);
return fn(...args);
}
你的 function 将成为
async function execute(interaction){
// It gets the pickaxe details
const pickaxe = require('../${pickaxeId}.js');
// This gets the time to mine stone, coal and iron from the pickaxe file
const timeToMineStone = pickaxe.stone
const timeToMineCoal = pickaxe.coal
const timeToMineIron = pickaxe.iron
const minableBlocks = ['stone', 'coal', 'iron']
var miningTime
// It picks one block randomly from the minableBlocks and depending on it, it assigns a value to the miningTime variable
// Code for picking the random block
for (var mined = 0; mined <= 100; mined++) {
timeout( () => {
console.log('Time Out!')
}, miningTime)
// Rest of the code should only be executed after the setTimeout()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.