In this article, we will learn how to create Stop Watch in react-js.
We can create Stop Watch in ReactJS using the following approach. Our StopWatch will have the functionality of Start, Pause, Resume and Reset.
First of all, we have to create a react application.
- npx create-react-app react-stop-watch
Using the Component:
- Five State used in the stopwatch component.
const [hours, setHours] = useState(0); const [minutes, setMinutes] = useState(0); const [seconds, setSeconds] = useState(0); const [milisec, setMilisec] = useState(0); const [state, setState] = useState(false); let timer; useEffect(() => { if (state) { timer = setInterval(() => { setMilisec((prevState) => prevState + 1) }, 10); } else if (!state) { clearInterval(timer) } return () => clearInterval(timer); }, [state])
- Stop-watch Start, Stop, Reset button function:
const start = () => { setState(true); } const pause = () => { clearInterval(timer); setState(false) } const reset = () => { setHours(0); setMinutes(0); setSeconds(0); setMilisec(0); setState(false) }
if (milisec === 99) { setSeconds((prevState) => prevState + 1) setMilisec(0) } if (seconds === 60) { setMinutes((prevstate) => prevstate + 1); setSeconds(0); } if (minutes === 60) { setHours((prevstate) => prevstate + 1); setMinutes(0); }
My App.js will look like this
import React, { useEffect, useState } from 'react' const App = () => { const [hours, setHours] = useState(0); const [minutes, setMinutes] = useState(0); const [seconds, setSeconds] = useState(0); const [milisec, setMilisec] = useState(0); const [state, setState] = useState(false); let timer; useEffect(() => { if (state) { timer = setInterval(() => { setMilisec((prevState) => prevState + 1) }, 10); } else if (!state) { clearInterval(timer) } return () => clearInterval(timer); }, [state]) const start = () => { setState(true); } const pause = () => { clearInterval(timer); setState(false) } const reset = () => { setHours(0); setMinutes(0); setSeconds(0); setMilisec(0); setState(false) } if (milisec === 99) { setSeconds((prevState) => prevState + 1) setMilisec(0) } if (seconds === 60) { setMinutes((prevstate) => prevstate + 1); setSeconds(0); } if (minutes === 60) { setHours((prevstate) => prevstate + 1); setMinutes(0); } return ( <div className="container"> <div className="time"> <span className="minute"> {hours < 10 ? "0" + hours : hours} </span> <span>:</span> <span className="minute"> {minutes < 10 ? "0" + minutes : minutes} </span> <span>:</span> <span className="second"> {seconds < 10 ? "0" + seconds : seconds} </span> <span>:</span> <span className="second"> {milisec < 10 ? "0" + milisec : milisec} </span> </div> <div className="buttons"> <button onClick={start} className="start"> Start </button> <button onClick={pause} className="pause"> Pause </button> <button onClick={reset} className="reset"> Reset </button> </div> </div> ) } export default App
Output: