Stopwatch

Why? Teaches setInterval(), clearInterval(), and time calculation.

<h2 id="time">00:00:00</h2>
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
<button onclick="reset()">Reset</button>

<script>
let sec = 0, min = 0, hr = 0;
let timer;

function start() {
  timer = setInterval(run, 1000);
}

function run() {
  sec++;
  if(sec == 60) { sec=0; min++; }
  if(min == 60) { min=0; hr++; }

  document.getElementById("time").innerText =
${hr.toString().padStart(2,'0')}:${min.toString().padStart(2,'0')}:${sec.toString().padStart(2,'0')};
} function stop() { clearInterval(timer); } function reset() { clearInterval(timer); sec=0;min=0;hr=0; document.getElementById("time").innerText="00:00:00"; } </script>

Explanation:

  • setInterval() increases seconds every second.
  • Handles minute/hour rollover.
  • Stop and reset with clearInterval().

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *