Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda