forked from mattt0204/use-effect-timer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimer.jsx
46 lines (41 loc) · 1.12 KB
/
Timer.jsx
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
36
37
38
39
40
41
42
43
44
45
46
import { useState } from "react";
function Timer() {
const [timer, setTimer] = useState(10);
const [isStart, setIsStart] = useState(false);
const [timerInterval, setTimerInterval] = useState(null);
const handleStart = () => {
setIsStart((isStart) => !isStart);
if (!isStart) {
const interval = setInterval(() => {
setTimer((timer) => {
if (timer === 0) {
alert("시간이 종료되었습니다!");
setIsStart(false);
setTimer(10);
clearInterval(interval);
return timer;
}
return timer - 1;
});
}, 1000);
setTimerInterval(interval);
} else {
clearInterval(timerInterval);
}
};
const handleReset = () => {
setTimer(10);
clearInterval(timerInterval);
setIsStart(false);
};
return (
<>
<h1>1. Timer</h1>
<p>useEffect 훅 활용하기</p>
<p>0:{timer < 10 ? `0${timer}` : timer}</p>
<button onClick={handleStart}>{isStart ? "정지" : "시작"}</button>
<button onClick={handleReset}>리셋</button>
</>
);
}
export default Timer;