Javascript cumulative counter

Asked

Viewed 624 times

2

It is possible an infinite and accumulative counter where the puddle determines the time it will increase, for example:

Every 1 minute the number goes up, 3.001, 3.002, 3.003, and so on. And also it cannot be restarted every refresh.

I’m currently using the following code, it serves 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;
 }
  • 1

    Why don’t you save the start moment of the countdown in the localstorage or cookie and then read "the time that’s passed" from that moment on? You need to have this value in a string with format x.xxx?

  • Yes I need to have in this format, to follow a pattern of other numbers that I have on the same screen but that are not counters... I’ll take a look at this option you suggested.

1 answer

0

Well, you can implement this function that will always return the current counter 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.

The date subtraction returns millennia. So just divide by 1000 and 60 to get the counter for each minute.

Whenever you call getCounter() will return the current count. Then you use as you wish.

I thought it would be okay to pass an argument so you have more than one accountant 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.