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

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

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 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!