Skip to content

Commit

Permalink
refact: useInterval 优化
Browse files Browse the repository at this point in the history
  • Loading branch information
crazylxr committed Jul 8, 2021
1 parent 56484be commit 94f3a2f
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions packages/hooks/src/useInterval/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useEffect, useRef } from 'react';
import { useEffect } from 'react';
import useMemoizedFn from '../useMemoizedFn';

function useInterval(
fn: () => void,
Expand All @@ -9,21 +10,20 @@ function useInterval(
): void {
const immediate = options?.immediate;

const fnRef = useRef<() => void>();
fnRef.current = fn;
const memoFn = useMemoizedFn(fn);

useEffect(() => {
if (delay === undefined || delay === null) return;
if (immediate) {
fnRef.current?.();
memoFn();
}
const timer = setInterval(() => {
fnRef.current?.();
memoFn();
}, delay);
return () => {
clearInterval(timer);
};
}, [delay]);
}, [delay, memoFn]);
}

export default useInterval;

0 comments on commit 94f3a2f

Please sign in to comment.