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

158
Views
¿Cómo llenar un elemento después de que finaliza un setTimeout?

Estoy haciendo un efecto de "número ascendente" con la moneda. La página se carga y luego comienza un conteo extremadamente rápido desde 0.00 hasta un número decimal dado por una API. Estoy usando un setTimeout dentro de un bucle for. Todo hasta aquí funciona bien, pero cuando finaliza el bucle for, el número después del punto decimal es 00. Si la API devuelve $7000,50, el resultado final es $7000,00 en el HTML. Traté de cambiar el elemento innerHTML con el valor real de la API, pero se ejecuta antes del ciclo for, incluso si hago un .then() o una devolución de llamada.

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

Una solución podría ser colocar la última línea dentro del bucle for y hacer que se ejecute en la iteración final:

 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) } }) }

Esto hará que se ejecute después del bucle for.

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!