Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda