Home > Net >  Javascript number counter with cache
Javascript number counter with cache

Time:10-29

I have this script for to increment a counter by one after 1 second , but when I refresh the page I need to remember the last number I counted.

Example: Currently, I have 40. When I refresh the page I need to start counting after 40 not reset to 1. Is this possible?

function animateValue(id) {
  var obj = document.getElementById(id);
  var current = parseInt(obj.innerHTML);
  setInterval(function() {
    current  ;
    // Update the contents of the element
    obj.innerHTML = current;
  }, 1000);
}

animateValue('value');
<h1>
  <div id="value">1</div>
</h1>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can store the counter progress in localStorage, then retrieve the value on page load and start counting from there:

var obj = document.getElementById(id);
let counterStorage = localStorage.getItem('counter')
if(counterStorage) obj.innerHTML = counterStorage

function animateValue(id) {
    var current = parseInt(obj.innerHTML);
    setInterval(function() {
        current  ;
        localStorage.setItem('counter', current)
        obj.innerHTML = current;
    }, 1000);
}

animateValue('value');

CodePudding user response:

Use localstorage. If not exists then set and if exists use the value from localstorage.

function animateValue(id){    
    const obj = document.getElementById(id);
    let current = parseInt(obj.innerHTML);
    const storageTime = localStorage.getItem("mytime")
    if ( storageTime === null) {
       localStorage.setItem("mytime", current); 
    } else {
      current = storageTime;
    }
    
    setInterval(function(){        
        current  ;
        localStorage.setItem("mytime", current); 
        // Update the contents of the element
        obj.innerHTML = current;
    },1000);
}

animateValue('value');
 <h1><div id="value">1</div></h1>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

you can use window.localstorage. the code will look something like this

window.localstorage.set('timer', timer)

CodePudding user response:

But i have div for start number <div id="value">1</div>

  • Related