Home > Enterprise >  How to fill an element after a setTimeout is over?
How to fill an element after a setTimeout is over?

Time:10-31

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>

CodePudding user response:

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.

  • Related