以一般邏輯來寫
import React, { useState, useEffect, useRef } from 'react';
const Stopwatch = () => {
const [time, setTime] = useState(0);
const [isRunning, setIsRunning] = useState(false);
const intervalRef = useRef(null);
useEffect(() => {
if (isRunning) {
intervalRef.current = setInterval(() => {
setTime((prevTime) => prevTime + 0.01);
}, 10);
}
return () => clearInterval(intervalRef.current);
}, [isRunning]);
const start = () => {
setIsRunning(true);
};
const pause = () => {
setIsRunning(false);
};
const reset = () => {
setIsRunning(false);
setTime(0);
};
const formatTime = (time) => {
const minutes = Math.floor(time / 60);
const seconds = Math.floor(time % 60);
const milliseconds = Math.floor((time % 1) * 100);
return `${minutes.toString().padStart(2, '0')}:${seconds
.toString()
.padStart(2, '0')}.${milliseconds.toString().padStart(2, '0')}`;
};
return (
<div>
<h1>Stopwatch</h1>
<div>
{}
<p>{formatTime(time)}</p>
</div>
<div>
{}
{!isRunning ? (
<button onClick={start}>Start</button>
) : (
<button onClick={pause}>Pause</button>
)}
{}
<button onClick={reset}>Reset</button>
</div>
</div>
);
};
export default Stopwatch;