xxxxxxxxxx
const Stopwatch = () => {
const [time, setTime] = useState(0);
const [running, setRunning] = useState(false);
useEffect(() => {
let interval;
if (running) {
interval = setInterval(() => {
setTime((prevTime) => prevTime + 10);
}, 10);
} else if (!running) {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [running]);
return (
<div className="stopwatch">
<div className="numbers">
<span>{("0" + Math.floor((time / 60000) % 60)).slice(-2)}:</span>
<span>{("0" + Math.floor((time / 1000) % 60)).slice(-2)}:</span>
<span>{("0" + ((time / 10) % 100)).slice(-2)}</span>
</div>
<div className="buttons">
<button onClick={() => setRunning(true)}>Start</button>
<button onClick={() => setRunning(false)}>Stop</button>
<button onClick={() => setTime(0)}>Reset</button>
</div>
</div>
);
};
Code language: JavaScript (javascript)
xxxxxxxxxx
// *Stopwatch
import { useEffect, useState } from "react";
const StopwatchTry = () => {
const [time, setTime] = useState({
min: 0,
sec: 0,
});
const [runing, setRunning] = useState(false);
useEffect(() => {
let interval;
if (runing) {
interval = setInterval(() => {
setTime((prev) => ({
prev,
sec: prev.sec + 1,
}));
}, 1000);
} else {
clearInterval(interval);
}
return () => {
clearInterval(interval);
};
}, [runing]);
const start = () => {
setRunning(true);
};
const stop = () => {
setRunning(false);
};
const reset = () => {
setTime({
min: 0,
sec: 0,
});
};
return (
<>
<div>
{time.min}m {time.sec}s
</div>
<div>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
<button onClick={reset}>Reset</button>
</div>
</>
);
};
export default StopwatchTry;