-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstopwatch.js
More file actions
35 lines (29 loc) · 730 Bytes
/
Copy pathstopwatch.js
File metadata and controls
35 lines (29 loc) · 730 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { useEffect, useState } from "react";
export default function Stopwatch() {
const [seconds, setSeconds] = useState(0);
const [running, setRunning] = useState(false);
useEffect(() => {
if (!running) return;
const intervalId = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
return () => {
clearInterval(intervalId);
};
}, [running]);
return (
<div>
<h2>{seconds}s</h2>
<button onClick={() => setRunning(true)}>Start</button>
<button onClick={() => setRunning(false)}>Stop</button>
<button
onClick={() => {
setRunning(false);
setSeconds(0);
}}
>
Reset
</button>
</div>
);
}