How to build a stopwatch using JavaScript and React.js

js dom js dom react hook

Stopwatch App: The App will display the seconds in numbers and buttons to start, pause ,reset the interval


Stopwatch App App using Dom Manipulation:-

     
// Html code:

<div id="banner"><span>StopWatch</span></div>
<div id="clock">0</div>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>

// JavaScript code:

const display = document.getElementById("clock");
const startButton = document.getElementById("start");
const pauseButton = document.getElementById("pause");
const resetButton = document.getElementById("reset");
let interval;
let temp = 0;

function updateClock() {
  temp++;
  display.textContent = temp;
}

startButton.addEventListener("click", function () {
  if (!interval) {
    interval = setInterval(updateClock, 1000);
  }
});

pauseButton.addEventListener("click", ()=> {
  clearInterval(interval);
  interval = null;
});

resetButton.addEventListener("click", function () {
  clearInterval(interval);
  interval = null;
  temp = 0;
  display.textContent = temp;
});
  
  

StopWatch App using react useState, useEffect hooks and setInterval,clearInterval :-

  
  import React, { useState, useEffect } from 'react';

  function StopWatch() {
  const [time, setTime] = useState(0);
  const [isRunning, setIsRunning] = useState(false);
  let timerID;

  useEffect(() => {
    if (isRunning) {
      timerID = setInterval(() => {
        setTime((prevTime) => prevTime + 1);
      }, 1000);
    }

    return () => {
      clearInterval(timerID);
    };
  }, [isRunning]);

  const startClock = () => {
    if (!isRunning) {
      setIsRunning(true);
    }
  };

  const pauseClock = () => {
    setIsRunning(false);
  };

  const resetClock = () => {
    clearInterval(timerID);
    setTime(0);
    setIsRunning(false);
  };

  return (
    <div id="banner"><span>StopWatch</span></div>
    <div id="clock">{time}</div>
    <button id="start">Start</button>
    <button id="pause">Pause</button>
    <button id="reset">Reset</button>
  );
  }
  export default StopWatch;