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

236
Visualizações
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.

over 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

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.

over 4 years ago · Juan Pablo Isaza Relatório

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);
over 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
Assistente virtual