Skip to content

Commit 4b099c1

Browse files
committed
use single seconds state in useStopwatch
1 parent 8ca3324 commit 4b099c1

File tree

1 file changed

+13
-45
lines changed

1 file changed

+13
-45
lines changed

src/useStopwatch.js

Lines changed: 13 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,22 @@
11
import { useState, useEffect, useRef } from 'react';
2+
import { Time } from './utils';
23

34
export default function useStopwatch(settings) {
45
const { autoStart } = settings || {};
56

67
const [seconds, setSeconds] = useState(0);
7-
const [minutes, setMinutes] = useState(0);
8-
const [hours, setHours] = useState(0);
9-
const [days, setDays] = useState(0);
108
const intervalRef = useRef();
119

12-
function addDay() {
13-
setDays((prevDays) => (prevDays + 1));
14-
}
15-
16-
function addHour() {
17-
setHours((prevHours) => {
18-
if (prevHours === 23) {
19-
addDay();
20-
return 0;
21-
}
22-
return prevHours + 1;
23-
});
24-
}
25-
26-
function addMinute() {
27-
setMinutes((prevMinutes) => {
28-
if (prevMinutes === 59) {
29-
addHour();
30-
return 0;
31-
}
32-
return prevMinutes + 1;
33-
});
34-
}
35-
36-
function addSecond() {
37-
setSeconds((prevSeconds) => {
38-
if (prevSeconds === 59) {
39-
addMinute();
40-
return 0;
41-
}
42-
return prevSeconds + 1;
43-
});
10+
function clearIntervalRef() {
11+
if (intervalRef.current) {
12+
clearInterval(intervalRef.current);
13+
intervalRef.current = undefined;
14+
}
4415
}
4516

4617
function start() {
4718
if (!intervalRef.current) {
48-
intervalRef.current = setInterval(() => addSecond(), 1000);
19+
intervalRef.current = setInterval(() => setSeconds((prevSeconds) => (prevSeconds + 1)), 1000);
4920
}
5021
}
5122

@@ -57,25 +28,22 @@ export default function useStopwatch(settings) {
5728
}
5829

5930
function reset() {
60-
if (intervalRef.current) {
61-
clearInterval(intervalRef.current);
62-
intervalRef.current = undefined;
63-
}
31+
clearIntervalRef();
6432
setSeconds(0);
65-
setMinutes(0);
66-
setHours(0);
67-
setDays(0);
33+
if (autoStart) {
34+
start();
35+
}
6836
}
6937

7038
// didMount effect
7139
useEffect(() => {
7240
if (autoStart) {
7341
start();
7442
}
75-
return reset;
43+
return clearIntervalRef;
7644
}, []);
7745

7846
return {
79-
seconds, minutes, hours, days, start, pause, reset,
47+
...Time.getTimeFromSeconds(seconds), start, pause, reset,
8048
};
8149
}

0 commit comments

Comments
 (0)