stopwatch
The interval ID needs to be saved in the ref so that the timer can be cleared when needed.
import {
useRef, useState } from "react";
const SecondWatch = () => {
const [startTime, setStartTime] = useState<any>(null);
const [now, setNow] = useState<any>(null);
const intervalRef = useRef<any>(null);
function handleStart() {
// Date.now() 用于获取当前时间的时间戳。它返回的是一个表示当前时间的整数值,以毫秒为单位。
setStartTime(Date.now());
setNow(Date.now());
// 清除上一个定时器
clearInterval(intervalRef.current);
// 定时器
intervalRef.current = setInterval(() => {
setNow(Date.now());
}, 10);
}
function handleStop() {
// 关闭定时器
clearInterval(intervalRef.current);
}
let secondsPassed = 0;
// 毫秒数除以 1000,以将其转换为秒。
if (startTime != null && now != null) {
secondsPassed = (now - startTime) / 1000;
}
return (
<>
<h1>秒表计时: {
secondsPassed.toFixed(3)}</h1>
<button onClick={
handleStart}>开始</button>
<button onClick={
handleStop}>暂停</button>
</>
);
};
export default SecondWatch;
Using useRef
creates a intervalRef
reference object named with an initial value of null
. When the "Start" button is clicked, I clear any previous timers that may have existed (if any) and create a new one. The ID of the timer is stored in intervalRef.current
.
When the "Stop" button is clicked, I clear the current timer and intervalRef.current
reset to null
.
In this way, we use intervalRef.current
to save and update the ID of the timer, and the timer can be cleared when needed, while avoiding displaying the timer on the interface.