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