我正在為使用 Discord.js API 的不和諧機器人制作游戲,如果變數播放(真/假)沒有改變,我嘗試在 10 秒后運行代碼(以避免第一人完成他的游戲和第二個人啟動一個新游戲并在幾秒鐘后開始計時),所以我已經完成了 10 秒計時器但我無法解決第二個問題,所以這是我的代碼的簡化版本:
if(message.content === "?guess"){
playing = true;
setTimeout(function(){
message.reply("time's up!");
playing = false;
}, 10000);
}
uj5u.com熱心網友回復:
只需在 setTimeout 回呼中添加一個 if 條件來檢查他們是否仍在玩,然后才結束游戲。
const globalGameTimeout = null;
...
if(message.content === "?guess"){
playing = true;
globalGameTimeout = setTimeout(function(){
if (playing) {
message.reply("time's up!");
playing = false;
}
}, 10000);
}
....
if (user guessed correctly or game ends in some other way) {
clearTimeout(globalGameTimeout);
}
clearTimeout(..) 將確保舊的 setTimeout 不會在其他玩家結束之前的游戲并開始新的游戲時仍然錯誤地執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470105.html
標籤:javascript 不和谐.js