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

205
Visualizações
Playing animation during x seconds using setInterval

I want to display an animated number from 0 to max value y during x seconds. I have tried this following code but it take too much to complete and clear the interval.

jQuery('.numbers').each(function(item, index) {
  const $obj = jQuery(this);
  let objValue = parseInt($obj.text()),
    currentValue = 0,
    speed = 1,
    time = 4000,
    step = Math.floor(objValue / time);
  $obj.text(currentValue);
  let interVal = setInterval(() => {
    if (currentValue >= objValue) {
      clearInterval(interVal);
      $obj.text(objValue);
    }
    $obj.text(currentValue);
    currentValue += step
  }, speed);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='numbers'>7586</span>
<span class='numbers'>147520</span>

How do I play this animation during exactly time seconds?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It is better not to depend on the timing of setInterval(), but the real problem in your script is that you use the floored value to decide the new value to print out.

It is better to use Window.requestAnimationFrame() and create a update() function that prints the current number based on the real time elapsed.

let start, previousTimeStamp;
let numbers = document.querySelectorAll('.numbers');

requestAnimationFrame(update);

function update(timestamp) {
  if (start === undefined) {
    start = timestamp;
  }
  const elapsed = timestamp - start;
  [...numbers].forEach(elm => {
    if(!elm.dataset.start){
      elm.dataset.start = elm.textContent;
    }
    let start = parseInt(elm.dataset.start);
    elm.textContent = Math.floor(start / 4000 * elapsed);
  });
  if (elapsed < 4000) {
    previousTimeStamp = timestamp;
    requestAnimationFrame(update);
  }else {
    start = undefined;
    [...numbers].forEach(elm => {
      elm.textContent = elm.dataset.start;
    });
  }
}
<span class='numbers'>7586</span>
<span class='numbers'>147520</span>

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