Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
Javascript number counter with cache

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>

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

var obj = document.getElementById("value");
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');
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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

window.localstorage.setItem('timer', timer)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!