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

252
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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
Recomende algumas ofertas para mim
Preciso de ajuda