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

168
Views
How to fill an element after a setTimeout is over?

I'm making an "ascending number" effect with currency. The page loads and then a extremely fast count start from 0.00 to a decimal number given by an API. I'm using a setTimeout inside a for loop. Everything until here works fine but when the for loops ends, the number after the decimal point is 00. If the API return $7000.50 the final result is $7000.00 in the HTML. I tried to change the innerHTML element with the actual API value but it's executed before the for loop, even if I make a .then() or callback.

JS:

function getTotalIncome() {
 fetch('/Invoices/GetProviderTotalIncome')
.then(res => res.json())
.then(function (data){
  for (let i = 0.0; i <= data; i++) {
    setTimeout(function () {
      document.getElementById('totalIncome').innerHTML = i.toFixed(2)
    }, 50)
  }
  document.getElementById('totalIncome').innerHTML = data.toFixed(2) //Why this is called before the for loop?
 })
}

HTML:

<h4 class="text-center">Total Invoices Value:
  <b>$<span id="totalIncome"></span></b>
</h4>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

One solution might be to put the final line inside of the for loop and have it execute on the final iteration:

 function getTotalIncome() {
 fetch('/Invoices/GetProviderTotalIncome')
 .then(res => res.json())
 .then(function (data){
   for (let i = 0.0; i <= data; i++) {
     setTimeout(function () {
       document.getElementById('totalIncome').innerHTML =      i.toFixed(2)

      // this will execute on final iteration, when for loop ends
      if(i == data ){
          document.getElementById('totalIncome').innerHTML       = data.toFixed(2)
         }
          }, 50)
           }

            })
          }

This will cause it to execute after the for 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!