簡體   English   中英

如何在 for 循環中使用 setTimeout

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM