Skip to content

Instantly share code, notes, and snippets.

@Manntrix
Created February 5, 2023 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Manntrix/f5d0a3b225d3ed2cf94263f83a11047c to your computer and use it in GitHub Desktop.
Save Manntrix/f5d0a3b225d3ed2cf94263f83a11047c to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react";
import "./stopwatch.css";
const Stopwatch = () => {
// state to store time
const [time, setTime] = useState(0);
// state to check stopwatch running or not
const [isRunning, setIsRunning] = useState(false);
useEffect(() => {
let intervalId;
if (isRunning) {
// setting time from 0 to 1 every 10 milisecond using javascript setInterval method
intervalId = setInterval(() => setTime(time + 1), 10);
}
return () => clearInterval(intervalId);
}, [isRunning, time]);
// Hours calculation
const hours = Math.floor(time / 360000);
// Minutes calculation
const minutes = Math.floor((time % 360000) / 6000);
// Seconds calculation
const seconds = Math.floor((time % 6000) / 100);
// Milliseconds calculation
const milliseconds = time % 100;
// Method to start and stop timer
const startAndStop = () => {
setIsRunning(!isRunning);
};
// Method to reset timer back to 0
const reset = () => {
setTime(0);
};
return (
<div className="stopwatch-container">
<p className="stopwatch-time">
{hours}:{minutes.toString().padStart(2, "0")}:
{seconds.toString().padStart(2, "0")}:
{milliseconds.toString().padStart(2, "0")}
</p>
<div className="stopwatch-buttons">
<button className="stopwatch-button" onClick={startAndStop}>
{isRunning ? "Stop" : "Start"}
</button>
<button className="stopwatch-button" onClick={reset}>
Reset
</button>
</div>
</div>
);
};
export default Stopwatch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment