Search code examples
javascriptcounterpersist

counter need persist to remember the last number


I found this fiddle: https://jsfiddle.net/DinoMyte/sac63azn/3/

https://fiddle.jshell.net/DinoMyte/sac63azn/3/show/

var num = 10000000;

setInterval(function()
  {   
    num++;
    console.log(num);
    $('div').text(num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
  },6000);

and it works almost the way I want it to. It is a counter where every 6 seconds, it will add a 1 to the number. For example: the number starts at 10,000,000 and then every 6 seconds, it adds a 1 to the number. The problem is when a user refresh or reloads the page, the number reverts back to the original 10,000,000. If after refresh or reload, is it possible the number will be saved from the last time? Persist? For example: the number is now 10,000,008, 6 seconds later it is 10,000,009, then the user click away or refresh or reloads the page, it should remember where the last number was left off: 10,000,009 and start counting from there.


Solution

  • You can use localStorage for this.

    Just use this code

    var num = localStorage.getItem('evaluatedTimer') || 10000000;
    
    setInterval(function()
      {   
        num++;
        console.log(num);
        var currentTimer = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        localStorage.setItem('evaluatedTimer', currentTimer');
        $('div').text(currentTimer );
      },6000);