-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseRandomInterval.ts
58 lines (49 loc) · 1.4 KB
/
useRandomInterval.ts
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
import { useCallback, useEffect, useRef, useState } from 'react';
import { random } from '../utils';
interface UseRandomIntervalReturnType {
start: () => void;
stop: () => void;
toggle: () => void;
active: boolean;
}
export const useRandomInterval = (
callback: () => void,
minDelay: number,
maxDelay: number,
): UseRandomIntervalReturnType => {
const timeoutId = useRef<number | null>(null);
const savedCallback = useRef<() => void>(callback);
const [active, setIsActive] = useState(false);
useEffect(() => {
savedCallback.current = callback;
});
const start = useCallback(() => {
const isEnabled = typeof minDelay === 'number' && typeof maxDelay === 'number';
if (isEnabled) {
const handleTick = () => {
const nextTickAt = random(minDelay, maxDelay);
timeoutId.current = window.setTimeout(() => {
savedCallback.current();
handleTick();
}, nextTickAt);
};
handleTick();
setIsActive(true);
}
}, [minDelay, maxDelay]);
useEffect(() => {
return () => window.clearTimeout(timeoutId.current!);
}, [minDelay, maxDelay]);
const stop = useCallback(() => {
window.clearTimeout(timeoutId.current!);
setIsActive(false);
}, []);
const toggle = useCallback(() => {
if (active) {
stop();
} else {
start();
}
}, [active, start, stop]);
return { start, stop, toggle, active };
};