I'm making a game for a discord bot that use the Discord.js API and I try to run a code after 10s if the variable playing (true/false) didn't change (to avoid a first person finish his game and a second person launch a new game and get time's up after a few seconds), so I already done the 10s timer but I can't resolve the second problem, so this is a simplified version of my code:
if(message.content === "?guess"){
playing = true;
setTimeout(function(){
message.reply("time's up!");
playing = false;
}, 10000);
}
Just add an if condition inside the setTimeout callback to check if they're still playing and only then end the game.
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);
}
The clearTimeout(..) will make sure that an old setTimeout doesn't still execute falsely when another player has ended the preivous game and started a new one.