You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
965 B
47 lines
965 B
4 years ago
|
import { useState, useEffect, useRef, useCallback } from 'react';
|
||
4 years ago
|
|
||
|
/**
|
||
|
* useTimeout
|
||
|
*
|
||
4 years ago
|
* @param {Function} cb - callback function inside setTimeout
|
||
|
* @param {number} delay - delay in ms
|
||
|
* @param {boolean} [immediate] - determines whether the timeout is invoked immediately
|
||
4 years ago
|
*
|
||
4 years ago
|
* @return {Function|undefined}
|
||
4 years ago
|
*/
|
||
4 years ago
|
export function useTimeout(cb, delay, immediate = true) {
|
||
4 years ago
|
const saveCb = useRef();
|
||
|
const [timeoutId, setTimeoutId] = useState(null);
|
||
4 years ago
|
|
||
|
useEffect(() => {
|
||
4 years ago
|
saveCb.current = cb;
|
||
|
}, [cb]);
|
||
4 years ago
|
|
||
|
useEffect(() => {
|
||
|
if (timeoutId !== 'start') {
|
||
4 years ago
|
return undefined;
|
||
4 years ago
|
}
|
||
|
|
||
|
const id = setTimeout(() => {
|
||
4 years ago
|
saveCb.current();
|
||
|
}, delay);
|
||
4 years ago
|
|
||
4 years ago
|
setTimeoutId(id);
|
||
4 years ago
|
|
||
|
return () => {
|
||
4 years ago
|
clearTimeout(timeoutId);
|
||
|
};
|
||
|
}, [delay, timeoutId]);
|
||
4 years ago
|
|
||
|
const startTimeout = useCallback(() => {
|
||
4 years ago
|
clearTimeout(timeoutId);
|
||
|
setTimeoutId('start');
|
||
|
}, [timeoutId]);
|
||
4 years ago
|
|
||
|
if (immediate) {
|
||
4 years ago
|
startTimeout();
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
return startTimeout;
|
||
4 years ago
|
}
|