Counter to a specific number

0

I have three counters, which go up to a certain number, defined as data-count-to of each tag, my problem here is that I liked them to reach their limit at the same time, even with values as different as is the case below:

function count_up(ele, count_to, timer, i) {
	if(i > count_to) {
		return;
	}
	ele.text(i.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1."));
	i += 1;
	/*console.log(timer);*/
	setTimeout(function() {count_up(ele, count_to, timer, i)}, timer);
}
$('.counter-up').each(function() {
	count_to = parseInt($(this).data('countTo'));
	timer = parseInt(40000/count_to);
	count_up($(this), count_to, timer, 0)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><spanclass="counter-up" data-count-to="5684"></span>
</div>
<div>
  <span class="counter-up" data-count-to="6603146"></span></div>
<div>
  <span class="counter-up" data-count-to="20362"></span>
</div>

Now, I think my problem is math in this case, because I suspect you have to also tweak the amount to increase as well, not just in time.

I would like the final result to be just that the argument to vary is the time, but with as long as the three counters come to the end of it at the same time

    
asked by anonymous 25.01.2018 / 13:40

1 answer

1

It is indeed a question of mathematics. My resolution proposes to increase the right amount in each timer, so that they all end at the same time.

To do this you need to:

  • To know the total time of the animation and the time between each frame of the animation
  • Divide the counter number by the total amount of "frames" of the animation that will give as each counter should increase to end at the right time.

Everything else is what I already had, even though I removed the function because it is a very short code and has changed setTimeout to setInterval .

See how it went:

const tempo_intervalo = 5; //ms -> define a velocidade da animação
const tempo = 4000; //ms -> define o tempo total da animaçao

$('.counter-up').each(function() {  
  let count_to = parseInt($(this).data('countTo'));
  let intervalos = tempo / tempo_intervalo; //quantos passos de animação tem
  let incremento = count_to / intervalos; //quanto cada contador deve aumentar
  let valor = 0;
  let el = $(this);
  
  let timer = setInterval(function() {
    if (valor >= count_to){ //se já contou tudo tem de parar o timer
      valor = count_to;
      clearInterval(timer);
    }
    
    let texto = valor.toFixed(0).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");
    el.text(texto);
    valor += incremento;      
  }, tempo_intervalo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><spanclass="counter-up" data-count-to="5684"></span>
</div>
<div>
  <span class="counter-up" data-count-to="6603146"></span></div>
<div>
  <span class="counter-up" data-count-to="20362"></span>
</div>
    
25.01.2018 / 15:34