import { useState, useEffect } from ‘react’;
import { Button } from “/components/ui/button”;
function Stopwatch() {
const [seconds, setSeconds] = useState(0);
const [isRunning, setIsRunning] = useState(false);
useEffect(() => {
let interval: number | null = null;
if (isRunning) {
interval = setInterval(() => {
setSeconds((prevSeconds) => prevSeconds + 1);
}, 1000);
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [isRunning]);
const handleStart = () => {
setIsRunning(true);
};
const handleStop = () => {
setIsRunning(false);
};
const handleReset = () => {
setIsRunning(false);
setSeconds(0);
};
return (
<div className=”flex flex-col items-center space-y-4″>
<p className=”text-4xl font-bold”>
{new Date(seconds * 1000).toISOString().slice(11, 19)}
</p>
<div className=”flex space-x-4″>
<Button onClick={handleStart} variant=”primary”>
Start
</Button>
<Button onClick={handleStop} variant=”secondary”>
Stop
</Button>
<Button onClick={handleReset} variant=”destructive”>
Reset
</Button>
</div>
</div>
);
}
export default Stopwatch;