JavaScript Local Storage Second Counter

my question is the following: Is it possible to create a second counter using local storage? I mean you load the page, the counter starts counting from 1 one by one. You reload the page at 5seconds, and the counter won’t resets but continues the counting from 5. Is it possible?

I have a code with a simple sec counter, but I don’t know how to make it workable with Local Storage

var seconds = 0;
var el = document.getElementById('seconds-counter');

function incrementSeconds() {
seconds += 1;
el.innerText = seconds;
}



var cancel = setInterval(incrementSeconds, 1000);
<div id='seconds-counter'> </div>

2 thoughts on “JavaScript Local Storage Second Counter”

  1. var el = document.getElementById('seconds-counter');
    
    function incrementSeconds() {
        var counter = window.localStorage.getItem("counter") ?? 0;
        window.localStorage.setItem("counter", ++counter);
        el.innerText = counter;
    }
    
    var cancel = setInterval(incrementSeconds, 1000);
    
    Reply
  2. this way

    const 
      div_s_counter = document.querySelector('#seconds-counter')
    , btStopCounter = document.querySelector('#bt-stop-counter')
    , timeRef_ls    = localStorage.getItem('startDate') || JSON.stringify(new Date())
    , timeRef       = new Date(JSON.parse(timeRef_ls))
    , CounterIntv   = setInterval(() =>
      {
      let now = new Date()
      div_s_counter.textContent = Math.floor(((new Date())-timeRef ) / 1000)
      }, 1000);
    ;
    localStorage.setItem('startDate', JSON.stringify(timeRef))
    
    btStopCounter.onclick = () =>
      {
      clearInterval( CounterIntv )
      localStorage.removeItem('startDate')
      }
    <div id="seconds-counter">_</div>
    
    <button id="bt-stop-counter"> stop counter </button>
    Reply

Leave a Comment