JavaScript Local Storage Second Counter

Viewed 485

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 Answers
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);

this way ?

<div id="seconds-counter">_</div>
<!-- button id="bt-stop-counter"> stop counter </button -->
const 
  counterLimit  = 5  // <-- your counter limit value....
, div_s_counter = document.querySelector('#seconds-counter')
, btStopCounter = document.querySelector('#bt-stop-counter')
, timeRef_ls    = localStorage.getItem('counterVal') || 0
, timeRef       = (new Date()) - (timeRef_ls * 1000)
, CounterIntv   = setInterval(() =>
  {
  let seconds = Math.floor(((new Date()) - timeRef) / 1000)

  if (seconds >= counterLimit )  // stopCounter()
    {
    div_s_counter.textContent = seconds = counterLimit
    clearInterval( CounterIntv ) 
    }
  div_s_counter.textContent = seconds
  localStorage.setItem('counterVal', seconds.toString(10))
  }
  , 500)
;
div_s_counter.textContent = timeRef_ls

/* disable counter reset ------------------------------------
  {
  clearInterval( CounterIntv )          // to stop the counter
  localStorage.removeItem('counterVal') // remove the counter
  }

btStopCounter.onclick = stopCounter
------------------------------------------------------------*/
Related