Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
Run a code after 10s if a variable didn't change

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);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda