ahooks
Version:
react hooks library
55 lines (54 loc) • 1.5 kB
JavaScript
import { useCallback, useEffect, useRef } from 'react';
import useLatest from '../useLatest';
import { isNumber } from '../utils';
const setRafTimeout = (callback, delay = 0) => {
if (typeof requestAnimationFrame === 'undefined') {
return {
id: setTimeout(callback, delay),
};
}
const handle = {
id: 0,
};
const startTime = Date.now();
const loop = () => {
const current = Date.now();
if (current - startTime >= delay) {
callback();
}
else {
handle.id = requestAnimationFrame(loop);
}
};
handle.id = requestAnimationFrame(loop);
return handle;
};
const cancelAnimationFrameIsNotDefined = (t) => {
return typeof cancelAnimationFrame === 'undefined';
};
const clearRafTimeout = (handle) => {
if (cancelAnimationFrameIsNotDefined(handle.id)) {
return clearTimeout(handle.id);
}
cancelAnimationFrame(handle.id);
};
function useRafTimeout(fn, delay) {
const fnRef = useLatest(fn);
const timerRef = useRef(undefined);
const clear = useCallback(() => {
if (timerRef.current) {
clearRafTimeout(timerRef.current);
}
}, []);
useEffect(() => {
if (!isNumber(delay) || delay < 0) {
return;
}
timerRef.current = setRafTimeout(() => {
fnRef.current();
}, delay);
return clear;
}, [delay]);
return clear;
}
export default useRafTimeout;