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

166
Views
setTimeout being called multiple times

I can't figure out why setTimeout is being called multiple times in my code. Here's a snippet of the code with what I thought was irrelevant removed:

let dead;

    setup()
    {
        dead = false;
    }
    
    draw()
    {
        if(fell == true)
        {
            dead = true;
        }
        mechanics();
    }
    
    function mechanics()
    {
        
        let triggerVar;
        
        if(dead == true)
        {   
            triggerVar = 1;
            
            dead = false;
        }
        
        if(triggerVar == 1)
        {
            setTimeout(resetG, 1500);
            triggerVar = 0;
        }
    }
    
    function resetG()
    {
        lives -= 1;
        position = 0;
    }

I can't tell what I'm doing wrong because whenever the character dies and setTimeout is called, it is actually not only called after the delay but also for the exact same duration after it is triggered. So in this case it is triggered first after 1500 millis and then every frame for another 1500 millis.

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

0

I managed to find the problem, which was not with the code I posted. The problem was that the constructor code that makes the object that changes dead to true if certain conditions are met was being called every frame from the moment it triggered death until the first instance of setTimeout kicked in, which means setTimeout was called every frame for 1500 milliseconds.

about 4 years ago · Juan Pablo Isaza Report

0

Chances are that you mechanics() function is called multiple times, you may give a variable to the settimeout like:

let timeoutID= setTimeout(resetG, 1500);

And in the proper place to clear it, for example after lifecycle

clearTimeout(timeoutID);
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!