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

214
Views
Reproducir animación durante x segundos usando setInterval

Quiero mostrar un número animado desde 0 hasta el valor máximo y durante x segundos. Probé el siguiente código, pero se necesita demasiado para completar y borrar el intervalo.

 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>

¿Cómo reproduzco esta animación durante exactamente los segundos de time ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Es mejor no depender del tiempo de setInterval() , pero el problema real en su secuencia de comandos es que usa el valor mínimo para decidir el nuevo valor para imprimir.

Es mejor usar Window.requestAnimationFrame() y crear una función de update() que imprima el número actual en función del tiempo real transcurrido.

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