forked from retyui/react-native-confirmation-code-field
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseTimer.ts
More file actions
29 lines (22 loc) · 702 Bytes
/
useTimer.ts
File metadata and controls
29 lines (22 loc) · 702 Bytes
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
import {useEffect, useRef} from 'react';
type ClearTimerFn = (id: number | undefined) => void;
type RunTimerFn = (handler: () => void, timeout: number) => number;
const creteUseTimer =
(clear: ClearTimerFn, runTimer: RunTimerFn) =>
(callback: () => void, delay: number): void => {
const timerRef = useRef<number>(undefined);
useEffect(() => {
const stop = () => clear(timerRef.current);
stop();
timerRef.current = runTimer(callback, delay);
return stop;
}, [delay]);
};
export const useInterval = creteUseTimer(
clearInterval as ClearTimerFn,
setInterval,
);
export const useTimeout = creteUseTimer(
clearTimeout as ClearTimerFn,
setTimeout,
);