Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda