Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!