Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda