Cumulative counter in javascript

2

An infinite and cumulative counter is possible where you can determine how long it will take, for example:

Every 1 minute the number goes up, 3.001, 3.002, 3.003, and so on. And tb it can not be restarted with every refresh.

I'm currently using the following code, it caters to me but not 100% the way I want it.

 $('.count').each(function() {
     $(this).prop('Counter', 0).animate({
         Counter: $(this).text()
     }, {
         duration: 200000,
         easing: 'swing',
         step: function(now) {
             $(this).text(commaSeparateNumber(Math.ceil(now)));
         }
     });
 });

 function commaSeparateNumber(val) {
     while (/(\d+)(\d{3})/.test(val.toString())) {
         val = val.toString().replace(/(\d+)(\d{3})/, '$1' + '.' + '$2');
     }
     return val;
 }
    
asked by anonymous 05.06.2016 / 22:43

1 answer

1

Well, you can implement this function that will always return the counter's current value.

The basic idea is to store the value of the current Date in localStorage and then whenever the function is called it calculates the time since then.

Date subtraction returns milegundo. So just divide by 1000 and by 60 to get the counter for every minute.

Whenever you call getCounter() it will return the current count. So you use whatever you want.

I was able to pass an argument to have more than one counter if you want, something like getCounter("contador1") and getCounter("contador2")

function getCounter(key){
    key = key ? key : "counterDefault";

    var valueLast = localStorage.getItem(key);
    var valueCurrent = new Date();

    if (valueLast == null) {
        valueLast = valueCurrent;
        localStorage.setItem(key, valueCurrent);
    }
    else {
        valueLast = new Date(valueLast);
    }

    var diff = valueCurrent - valueLast;

    diff = diff;    //Incrementa a cada milisegundo 
    diff /= 1000;   //Incrementa a cada segudo
    diff /= 60;     //Incrementa a cada minuto
    //diff /= 60;   //Incrementa a cada hora
    //diff /= 24;   //Incrementa a cada dia

    return parseInt(diff);
}
    
10.06.2016 / 17:24