Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

281
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!