Tengo 4 elementos de span dentro de un documento HTML que comienzan en 0 y quiero aumentar su valor en 1 hasta que lleguen a un valor marcado.
Todos deben terminar al mismo tiempo, incluso con valores diferentes.
Esta es la función que estoy usando, el parámetro del elemento es el span y el número es el número en el que quiero dejar de aumentar el valor.
let animateNumberInItem = (number,item) =>{ let startingNum = 0; let animationSpeed = 0; let interval = setInterval(()=>{ if(startingNum === number-1){ clearInterval(interval); } startingNum++; item.innerHTML = startingNum; },animationSpeed); };¿Alguna idea sobre cómo calcular el tiempo requerido para alcanzar el número en milisegundos usando el valor del número ?
Otra solución podría ser cambiar el número en que aumentan y/o el tiempo para hacerlos terminar al mismo tiempo.
Si aumenta el número startingNum en función de la proporción en la que están presentes los números objetivo, alcanzarán el objetivo al mismo tiempo.
let animateNumberInItem = (number,item, ratio) =>{ let startingNum = 0; let animationSpeed = 30; let interval = setInterval(()=>{ if(startingNum >= number){ clearInterval(interval); } else { // Increase the startingNum based on the ratio in which target number is present startingNum += ratio; item.innerHTML = Math.round(startingNum); } },animationSpeed); }; // eg first element has to reach target of 201 and second element has to reach target of 100 const ratio = 100/201; animateNumberInItem(201, document.getElementById('first'), 1); animateNumberInItem(100, document.getElementById('second'), ratio); <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <span id="first">0</span> <span id="second">0</span> </body> </html>Acabo de encontrar la solución y es más fácil de lo que parece.
Esta es la función editada:
let animateNumberInItem = (number,item) =>{ let startingNum = 0; let animationSpeed = 30; let animationGrowNumber = number / 100; let interval = setInterval(()=>{ if(startingNum >= number- animationGrowNumber){ clearInterval(interval); } startingNum+=animationGrowNumber; item.innerHTML = Math.round(startingNum); },animationSpeed); };Solo necesita dividir el número entre un valor (usé 100 porque da una animación más suave) y luego establecerlo como el valor creciente.
No aumentará en 1, pero la animación se ve bien de todos modos, también puede establecer el tiempo que desee porque no afecta el resultado final, solo la apariencia de la animación.