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

234
Visualizações
Get returned items from function inside setTimeout in Javascript

So I need a little delay in my JavaScript for a function inside a loop that should get called every 500 ms:

function myFunc(num) {
    return num++;
}

var theNum = 0;

while (theNum != 10) {
    theNum = setTimeout(myFunc(theNum), 500);
}
console.log("All done");

However, All done never gets logged.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. You're calling the function immediately. You need to pass the function reference to the setTimeout instead.

  2. And you're also creating an infinite loop due to that issue.

  3. Even if you corrected this problem "All done" would still be logged first before any of the timeouts completed.

So you need to rethink the approach. Put the timeout in a function and if theNum is less that 10 call the function again with the incremented number (setTimeout allows you to pass in arguments after the delay). Log "All done" when the count reaches 10.

function myFunc(num) {
  return `Number: ${num}`;
}

function loop(theNum = 0) {
  if (theNum < 10) {
    console.log(myFunc(theNum));
    setTimeout(loop, 500, ++theNum);
  } else {
    console.log("All done");
  }
}

loop();

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