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

282
Visualizações
How to wait for the recursive loop to finish and display the message?

I'm running a recursive function with setTimeout, what I've noticed is that javascript goes straight through the wait() function and doesn't wait for it to finish. It goes right through and leaves the wait() method working by itself.

wait(100, 30)

function wait(time, limit) {
    console.log('value >> ' + limit)
    if (limit < 0) return 'success'
    setTimeout(function () {
        wait(time, --limit)
    }, time)
}

console.log('hi')

Note that my "hi' message is at the top when running the script, because it went straight through without waiting for the recursive loop. My "hi" message should be at the end.

Can anyone help me leave the hi message at the end after running all the loop?

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

0

You could handover a function which is called at the end of waiting.

function wait(time, limit, fn) {
    console.log('value >> ' + limit)
    if (limit < 0) return fn();
    setTimeout(function () {
        wait(time, --limit, fn);
    }, time)
}

function sayHi() { console.log('hi'); }

wait(100, 30, sayHi);

about 4 years ago · Juan Pablo Isaza Relatório

0

you can also simply return the message which do you want:

wait(100, 30);

function wait(time, limit) {
  console.log("value >> " + limit);
  if (limit < 0) return console.log("hi");
  setTimeout(function () {
    wait(time, --limit);
  }, time);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

In addition to Nina's approach and also for use cases where a callback can not be implemented as easily as demonstrated with Nina's example code, one might use an abstraction for it, which for JavaScript is Promises.

Here, instead of 30 times delaying for 100 milliseconds until logging, one would implement wait as promise which resolves after 3 seconds with the additional logging provided as thenable ...

const wait = new Promise(resolve => setTimeout(resolve, 3000));

wait.then(() => console.log('hi'));

console.log({ wait: String(wait) });
.as-console-wrapper { min-height: 100%!important; top: 0; }

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