/
useInterval.js
54 lines (45 loc) 路 1.33 KB
/
useInterval.js
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
import { useEffect, useState, useCallback, useRef } from 'react';
const defaultOptions = {
cancelOnUnmount: true,
};
/**
* An async-utility hook that accepts a callback function and a delay time (in milliseconds), then repeats the
* execution of the given function by the defined milliseconds.
*/
const useInterval = (fn, milliseconds, options = defaultOptions) => {
const opts = { ...defaultOptions, ...(options || {}) };
const timeout = useRef();
const callback = useRef(fn);
const [isCleared, setIsCleared] = useState(false);
// the clear method
const clear = useCallback(() => {
if (timeout.current) {
clearInterval(timeout.current);
setIsCleared(true);
}
}, []);
// if the provided function changes, change its reference
useEffect(() => {
if (typeof fn === 'function') {
callback.current = fn;
}
}, [fn]);
// when the milliseconds change, reset the timeout
useEffect(() => {
// cleanup previous interval
clear();
if (typeof milliseconds === 'number') {
timeout.current = setInterval(() => {
callback.current();
}, milliseconds);
}
}, [milliseconds]);
// when component unmount clear the timeout
useEffect(() => () => {
if (opts.cancelOnUnmount) {
clear();
}
}, []);
return [isCleared, clear];
};
export default useInterval;