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

251
Views
how to execute code 3 seconds later once executed in a infinite loop

I am making a game using html canvas in which i want to check for certain condition every time in animate loop and if that condition become true once then I don't want to check for next 3 seconds and after 3 seconds i want to check again. Like

function animate(){
  requestAnimationFrame(animate)
  if (checking something){
    if this if statement gets executed then don't check this if statement for next 3 seconds 
  }

This might sound bit confusing but is there anyway to do this.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

My suggestion would be to add a flag - another variable that you can use to check if an operation should be done, and another function that'll toggle the flag after a certain amount of time.

// THE CHECKING FLAG
let shouldCheckCondition = true;

function animate(){
  requestAnimationFrame(animate)
  
  // CHECK THE FLAG FIRST, IF SHOULD NOT CHECK, EXIT THE FUNCTION
  if (!shouldCheckCondition) return;

  if (condition){
    // DISABLE THE CHECKING FLAG SO YOU SKIP THE SUBSEQUENT CHECKS
    shouldCheckCondition = false;

    // DO SOMETHING WHEN CONDITION IS MET AND CHECKING SHOULD BE DONE

    // ENABLE THE CHECKING FLAG AFTER 3 second
    setTimeout(() => { shouldCheckCondition = true; }, 3000);
  }
about 4 years ago · Juan Pablo Isaza Report

0

If you want to do it inline within another method, setInterval might not help.

You can just make a note of the last time you did that check (eg. system time in milliseconds) and then make sure that it is more than 3000ms after that when you next do the check.

date.valueOf(); //An existing date object to milliseconds format
(new Date()).valueOf(); //current time in ms

You can have two vars lastCheckedTime and currentTime.

about 4 years ago · Juan Pablo Isaza Report

0

requestAnimationFrame tries to run on the next frame, not after three seconds. So don't use requestAnimationFrame if you want three seconds.

function animate(){
    if (checking something){
        setTimeout(animate, 3000);
    } else {
        requestAnimationFrame(animate);
    }
}
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!