bbgo_origin/apps/frontend/hooks/useInterval.ts

21 lines
454 B
TypeScript
Raw Normal View History

2022-06-15 11:02:24 +00:00
import { useEffect, useRef } from 'react';
2022-06-15 03:33:21 +00:00
export default function useInterval(cb: Function, delayMs: number | null) {
const savedCallback = useRef<Function>();
2022-06-15 11:02:24 +00:00
2022-06-15 03:33:21 +00:00
useEffect(() => {
2022-06-15 11:02:24 +00:00
savedCallback.current = cb;
}, [cb]);
2022-06-15 03:33:21 +00:00
useEffect(() => {
function tick() {
savedCallback.current();
}
2022-06-15 11:02:24 +00:00
2022-06-15 03:33:21 +00:00
if (delayMs !== null) {
2022-06-15 11:02:24 +00:00
let timerId = setInterval(tick, delayMs);
return () => clearInterval(timerId);
2022-06-15 03:33:21 +00:00
}
2022-06-15 11:02:24 +00:00
}, [delayMs]);
}