-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathuseStopwatch.js
More file actions
65 lines (65 loc) · 2.23 KB
/
useStopwatch.js
File metadata and controls
65 lines (65 loc) · 2.23 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { useEffect, useState } from 'react';
const getStopwatchTime = (time) => {
if (!time)
return {
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
count: 0
};
const days = Math.floor(time / 86400);
const hours = Math.floor((time % 86400) / 3600);
const minutes = Math.floor((time % 3600) / 60);
const seconds = Math.floor(time % 60);
return { days, hours, minutes, seconds, count: time };
};
/**
* @name useStopwatch
* @description - Hook that creates a stopwatch functionality
* @category Time
* @usage high
*
* @overload
* @param {number} [initialTime=0] The initial time of the timer
* @param {boolean} [options.immediately=false] Start the stopwatch immediately
* @returns {UseStopwatchReturn} An object containing the current time and functions to interact with the timer
*
* @example
* const { seconds, minutes, start, pause, reset } = useStopwatch(1000, { immediately: false });
*
* @overload
* @param {number} [options.initialTime=0] The initial time of the timer
* @param {boolean} [options.immediately=false] Start the stopwatch immediately
* @returns {UseStopwatchReturn} An object containing the current time and functions to interact with the timer
*
* @example
* const { seconds, minutes, start, pause, reset } = useStopwatch({ initialTime: 1000, immediately: false });
*/
export const useStopwatch = (...params) => {
const initialTime = (typeof params[0] === 'number' ? params[0] : params[0]?.initialTime) ?? 0;
const options = typeof params[0] === 'number' ? params[1] : params[0];
const immediately = options?.immediately ?? false;
const [count, setCount] = useState(initialTime);
const [paused, setPaused] = useState(!immediately);
useEffect(() => {
setCount(initialTime);
}, [initialTime]);
useEffect(() => {
if (paused) return;
const onInterval = () => {
setCount((prevCount) => prevCount + 1);
};
const interval = setInterval(onInterval, 1000);
return () => clearInterval(interval);
}, [paused]);
const time = getStopwatchTime(count);
return {
...time,
paused,
pause: () => setPaused(true),
start: () => setPaused(false),
reset: () => setCount(initialTime),
toggle: () => setPaused((prevPause) => !prevPause)
};
};