Javascript Stopwatch. Need help to store my timer and when page refresh to keep the time and continue from there

I have a working stopwatch. When I click start button the stopwatch is starting and when I click pause button the stopwatch is paused. What I would like is when I refresh my browser to keep the current time of the stopwatch and continue from there with the same functionality. Or when I echo the stopwatch time from a database to continue from the exact time it was before is saved it.

let showTime = document.querySelector("#output");
let startTimeButton = document.querySelector("#start")
let pauseTimeButton = document.querySelector("#pause")
pauseTimeButton.style.display = "none";

let seconds = 0;
let interval = null;

const timer = () => {
  seconds++;

  // Get hours
  let hours = Math.floor(seconds / 3600);
  // Get minutes
  let minutes = Math.floor((seconds - hours * 3600) / 60);
  // Get seconds
  let secs = Math.floor(seconds % 60);

  if (hours < 10) {
    hours = `0${hours}`;
  }
  if (minutes < 10) {
    minutes = `0${minutes}`;
  }
  if (secs < 10) {
    secs = `0${secs}`;
  }

  showTime.innerHTML = `${hours}:${minutes}:${secs}`;

};

startTimeButton.addEventListener("click", () => {
  pauseTimeButton.style.display = "block";
  startTimeButton.style.display = "none";
  console.log("START TIME CLICKED");

  if (interval) {
    return;
  }

  interval = setInterval(timer, 1000);
});

// Pause function
pauseTimeButton.addEventListener("click", () => {
  pauseTimeButton.style.display = "none";
  startTimeButton.style.display = "block";
  console.log("PAUSE TIME CLICKED");
  clearInterval(interval);
  interval = null;

});
<button id="start">Start</button>
<button id="pause">Pause</button>
<div id="output"></div>

>Solution :

You could use localStorage.

In order to save each second passed you could modify your timer function to save to localStorage:


let seconds = 0;
if (localStorage.getItem("stopwatchSeconds") != null) {
    seconds = parseInt(localStorage.getItem("stopwatchSeconds"));
}


//...
const timer = () => {

    //...
    seconds++;
    localStorage.setItem("stopwatchSeconds", seconds);
    //...

};
//...

I hope this helps.

Leave a Reply