Skip to content

Commit a411dfd

Browse files
authored
fix(timer): reset timer if type or timeout were changed (#20)
1 parent 9f3a050 commit a411dfd

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

packages/components/timer/src/useTimer.ts

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useCallback, useEffect, useMemo, useState } from "react";
1+
import { useEffect, useMemo, useState } from "react";
22

33
type TimerType = "countup" | "countdown";
44

@@ -31,22 +31,29 @@ const calculateTimerState = (type: TimerType, startTime: number | null, timeout:
3131
};
3232

3333
export const useTimer = ({ timeout = 0, type = "countup", isCounting = false, onTimeOut }: UseTimerOptions) => {
34+
const [localTimeout, setLocalTimeout] = useState(timeout);
3435
const [{ seconds, minutes, timeLeft, timeLeftPercents }, setTimer] = useState(
35-
calculateTimerState(type, null, timeout)
36+
calculateTimerState(type, null, localTimeout)
3637
);
3738

3839
const [startTime, setStartTime] = useState<number | null>(isCounting ? Date.now() : null);
3940
const [endTime, setEndTime] = useState<number | null>(null);
4041
const [localIsCounting, setIsCounting] = useState(isCounting);
4142

42-
const computeTimer = useCallback(() => {
43-
setTimer(calculateTimerState(type, startTime, timeout));
44-
}, [startTime, timeout, type, setTimer, localIsCounting]);
45-
4643
useEffect(() => {
4744
setIsCounting(isCounting);
4845
}, [isCounting]);
4946

47+
useEffect(() => {
48+
setStartTime(null);
49+
setEndTime(null);
50+
setLocalTimeout(timeout);
51+
}, [timeout, type, setStartTime, setEndTime, setLocalTimeout]);
52+
53+
useEffect(() => {
54+
setTimer(calculateTimerState(type, startTime, timeout));
55+
}, [localTimeout, setTimer]);
56+
5057
useEffect(() => {
5158
if (localIsCounting && !startTime) {
5259
setStartTime(Date.now());
@@ -61,21 +68,25 @@ export const useTimer = ({ timeout = 0, type = "countup", isCounting = false, on
6168
}
6269
}, [timeLeft, type, onTimeOut]);
6370

64-
useEffect(() => {
65-
computeTimer();
66-
}, [computeTimer]);
71+
// useEffect(() => {
72+
// computeTimer();
73+
// }, [computeTimer]);
6774

6875
useEffect(() => {
6976
if (!localIsCounting) {
7077
return () => {};
7178
}
7279

80+
const computeTimer = () => {
81+
setTimer(calculateTimerState(type, startTime, timeout));
82+
};
83+
7384
const interval = setInterval(computeTimer, 1000);
7485

7586
return () => {
7687
clearInterval(interval);
7788
};
78-
}, [computeTimer]);
89+
}, [startTime, timeout, type, setTimer, localIsCounting]);
7990

8091
return useMemo(
8192
() => ({ timeLeft, minutes, seconds, timeLeftPercents, startTime, endTime, isCounting: localIsCounting }),

0 commit comments

Comments
 (0)