common-hook
Version:
提供项目中常用的 React Hooks
40 lines (39 loc) • 1.1 kB
JavaScript
//@ts-nocheck
import { useCallback, useEffect, useRef } from "react";
import { useLatest } from "common-hook";
import { isNumber } from "common-screw";
/**
* @name 处理setInterval的Hook
* @description 例如:每1000ms,执行一次
* @example
* useInterval(() => {
setCount(count + 1);
}, 1000);
*/
export const useInterval = (fn, delay, options) => {
const immediate = options === null || options === void 0 ? void 0 : options.immediate;
const fnRef = useLatest(fn);
const timerRef = useRef();
useEffect(() => {
//@ts-ignore
if (!isNumber(delay) || delay < 0)
return;
if (immediate) {
fnRef.current();
}
timerRef.current = setInterval(() => {
fnRef.current();
}, delay);
return () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
}, [delay]);
const clear = useCallback(() => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
}, []);
return clear;
};