-1

i have made a stopwatch using html and javascript as below(i got this code from a website).when i pressed start button it starts running and when i refresh the page it resets and starts running from the 00:00:00. I have no idea how to prevent it from resetting.Anyone have any idea? my code is:

HTML


    <h1><time>00:00:00</time></h1>
    <button id="start">start</button>
    <button id="stop">stop</button>
    <button id="clear">clear</button>

Javascript


    var h1 = document.getElementsByTagName('h1')[0],
        start = document.getElementById('start'),
        stop = document.getElementById('stop'),
        clear = document.getElementById('clear'),
        seconds = 0, minutes = 0, hours = 0,
        t;
    
    function add() {
        seconds++;
        if (seconds >= 60) {
            seconds = 0;
            minutes++;
            if (minutes >= 60) {
                minutes = 0;
                hours++;
            }
        }
        
        h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
    
        timer();
    }
    function timer() {
        t = setTimeout(add, 1000);
    }
    timer();
    
    
    /* Start button */
    start.onclick = timer;
    
    /* Stop button */
    stop.onclick = function() {
        clearTimeout(t);
    }
    
    /* Clear button */
    clear.onclick = function() {
        h1.textContent = "00:00:00";
        seconds = 0; minutes = 0; hours = 0;
    }

Akash
  • 89
  • 13

2 Answers2

1

You can store the data in the localstorage. Below is an edited version of your code. It still has lots of work to do, I also discovered some bugs, which at the moment I do not have time to cover.

But I believe this will give you a hint and is a good place to start.

var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
clearMemory = document.getElementById('clearMemory'),
seconds = 0, minutes = 0, hours = 0,
t,
endTime,
startTime = parseDate(localStorage.getItem("startTime")),
timerRunning = false;

function parseDate(input) {
  if (input) {
    return new Date(input); // months are 0-based
  }
  return null;
}

function add() {
  seconds++;
  if (seconds >= 60) {
    seconds = 0;
    minutes++;
    if (minutes >= 60) {
      minutes = 0;
      hours++;
    }
  }

  h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);

  timer();
}

function timer() {
  t = setTimeout(add, 1000);
}
// timer();

function startTimer() {
  if (!timerRunning) {
    endTime = new Date();
    if (!startTime) {
      localStorage.setItem("startTime", endTime);
      startTime = endTime;
    }
    seconds = parseInt((endTime.getTime() - startTime.getTime()) / 1000);
    timer();
  }
  timerRunning = true;
}
startTimer();
/* Start button */
start.onclick = startTimer;

/* Clear Memory */
clearMemory.onclick = function() {
  localStorage.removeItem("startTime");
}

/* Stop button */
stop.onclick = function() {
  timerRunning = false;
  clearTimeout(t);
}

/* Clear button */
clear.onclick = function() {
  h1.textContent = "00:00:00";
  seconds = 0; minutes = 0; hours = 0;
}

I also added a button to clear localstorage data

<h1><time>00:00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
<button id="clearMemory">clear memory</button>

EDİT: Below is another example of a timer. But this time I used Javascript Classes. Not the best way but seems more proffesional.

const stopWatch = document.getElementById('stopWatch')
const startBtn = document.getElementById('start')
const stopBtn = document.getElementById('stop')
const clearBtn = document.getElementById('clear')
const speedBtn = document.getElementById('speed')

class Timer {
  constructor(speed = 1) {
    this.speed = speed
    this.passed = localStorage.getItem("stopWatch") || 0
    this.running = localStorage.getItem("running") === 'true' || false
    this.interval = null
    this.time = this.calculate()
    this.init()
  }

  init = () => {
    if (this.running) {
      this.start()
    }
    this.show()
  }

  show = () => {
    var H = this.format(this.time.h)
    var M = this.format(this.time.m)
    var S = this.format(this.time.s)
    stopWatch.textContent = H + ':' + M + ':' + S
  }

  calculate = () => {
    // Thanks to Alnitak's answer on StackOverflow
    // https://stackoverflow.com/questions/13903897/javascript-return-number-of-days-hours-minutes-seconds-between-two-dates/13904621
    let delta = this.passed || 0
    let h = Math.floor(delta / 3600)
    delta -= h*3600
    let m = Math.floor(delta / 60) % 60;
    delta -= m*60
    let s = parseInt(delta % 60);
    return {h:h, m:m, s:s}
  }

  update = () => {
    this.passed ++
    this.time = this.calculate()
    localStorage.setItem("stopWatch", this.passed);
    this.show()
  }

  start = () => {
    this.running = true
    startBtn.disabled = true
    stopBtn.disabled = false
    localStorage.setItem("running", true);
    this.interval = setInterval(() => this.update(), 1000/this.speed)
  }

  stop = () => {
    clearInterval(this.interval)
    localStorage.setItem("running", false);
    startBtn.disabled = false
    stopBtn.disabled = true
  }

  clear = () => {
    this.time = {h:0, m:0, s:0}
    this.passed = 0
    this.stop()
    this.show()
    localStorage.removeItem("stopWatch")
  }

  setSpeed = () => {
    this.speed = speedBtn.value
  }

  format = (n) => {
    return n.toLocaleString('en-US', {
      minimumIntegerDigits: 2,
      useGrouping: false
    })
  }

}



const timer = new Timer()

startBtn.onclick = () => timer.start() // This arrow notation is a must here, or else timer starts immediately
clearBtn.onclick = () => timer.clear()
stopBtn.onclick = () => timer.stop()
speedBtn.onchange = () => timer.setSpeed()

And this is the HTML part:

<h1 id="stopWatch"><time></time></h1>
<button id="start">start</button>
<button id="stop" disabled>stop</button>
<button id="clear">clear</button>
<input type="range" min="1" max="100" value="1" class="slider" id="speed">

You can also change the speed on init like so: const timer = new Timer(10) (Increasing the speed by 10)

Rüzgar
  • 947
  • 9
  • 20
  • after 1min timer run.. when i refreshed the page it starts from 00:01:00 always – Akash Sep 03 '21 at 16:31
  • Yes, that was one of the bugs I mentioned. Should I have time tomorrow, I will try to find out how. But as I said, my answer was just a starter dor you to go on. – Rüzgar Sep 03 '21 at 18:53
  • I edited my answer, but used Javascript Classes this time. – Rüzgar Sep 04 '21 at 12:48
  • Notes: You probably want to use `setInterval` instead of `setTimeout`. You also probably want to disable the start button when it not stopped. Without doing that, double-pressing will cause the first "start"'s timeout token to be "lost", and the stop button will only stop the most recent "double-press". – starball Aug 16 '22 at 23:53
-1

Akash in your code there is a bug I think. If you reload, or refresh the page, when you start automatically the timer, it will increase the seconds with 2 instead of 1.