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

216
Visualizações
Trying to run a loop for exactly one second, but the loop runs infinitely. why?

i am changing the value of 'aa' after 1 second, but the loop continues to execute.

let aa = true;

setTimeout(function () {
  aa = false;
}, 1000);

for (; aa; ) {
  console.log('aaa');
}
about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

setTimeout is asynchronous, so it will execute only after the current code execution of for loop completed. In your case it will go infinite.

Once for loop started execution, it will stay in the call stack until finished. Since you didn't give any condition there it won't stop

about 4 years ago · Santiago Gelvez Relatório

0

Your approach doesn’t work for reasons explained by others. You can use something like this instead:

var started = Date.now();
while(Date.now() - started < 1000) {
  console.log("aaa");
};

about 4 years ago · Santiago Gelvez 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