Skip to content

Commit 0dae45f

Browse files
committed
add useInterval in useStopwatch
1 parent c7a1cdd commit 0dae45f

File tree

1 file changed

+9
-29
lines changed

1 file changed

+9
-29
lines changed

src/useStopwatch.js

Lines changed: 9 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,28 @@
1-
import { useState, useEffect, useRef } from 'react';
1+
import { useState } from 'react';
22
import { Time } from './utils';
3+
import { useInterval } from './hooks';
34

4-
export default function useStopwatch(settings) {
5-
const { autoStart, offsetTimestamp } = settings || {};
6-
5+
export default function useStopwatch({ autoStart, offsetTimestamp }) {
76
const [seconds, setSeconds] = useState(Time.getSecondsFromExpiry(offsetTimestamp || 0));
87
const [isRunning, setIsRunning] = useState(autoStart);
9-
const intervalRef = useRef();
108

11-
function clearIntervalRef() {
12-
if (intervalRef.current) {
13-
setIsRunning(false);
14-
clearInterval(intervalRef.current);
15-
intervalRef.current = undefined;
16-
}
17-
}
9+
useInterval(isRunning ? () => {
10+
setSeconds((prevSeconds) => (prevSeconds + 1));
11+
} : () => {}, 1000);
1812

1913
function start() {
20-
if (!intervalRef.current) {
21-
setIsRunning(true);
22-
intervalRef.current = setInterval(() => setSeconds((prevSeconds) => (prevSeconds + 1)), 1000);
23-
}
14+
setIsRunning(true);
2415
}
2516

2617
function pause() {
27-
clearIntervalRef();
18+
setIsRunning(false);
2819
}
2920

3021
function reset(offset: number) {
31-
clearIntervalRef();
22+
setIsRunning(autoStart);
3223
setSeconds(Time.getSecondsFromExpiry(offset || 0));
33-
if (autoStart) {
34-
start();
35-
}
3624
}
3725

38-
// didMount effect
39-
useEffect(() => {
40-
if (autoStart) {
41-
start();
42-
}
43-
return clearIntervalRef;
44-
}, []);
45-
4626
return {
4727
...Time.getTimeFromSeconds(seconds), start, pause, reset, isRunning,
4828
};

0 commit comments

Comments
 (0)