2023-01-13 10:30:09 +03:00
|
|
|
import { useEffect, useRef } from 'preact/hooks';
|
|
|
|
|
2023-05-05 12:53:16 +03:00
|
|
|
function useInterval(fn, delay, deps, immediate) {
|
|
|
|
const savedCallback = useRef(fn);
|
2023-01-13 10:30:09 +03:00
|
|
|
useEffect(() => {
|
2023-05-05 12:53:16 +03:00
|
|
|
savedCallback.current = fn;
|
2023-07-13 15:11:23 +03:00
|
|
|
}, [fn, deps]);
|
2023-02-08 14:11:33 +03:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (!immediate || delay === null || delay === false) return;
|
|
|
|
savedCallback.current();
|
|
|
|
}, [immediate]);
|
2023-01-13 10:30:09 +03:00
|
|
|
|
|
|
|
useEffect(() => {
|
2023-02-08 14:11:33 +03:00
|
|
|
if (delay === null || delay === false) return;
|
|
|
|
const tick = () => savedCallback.current();
|
|
|
|
const id = setInterval(tick, delay);
|
|
|
|
return () => clearInterval(id);
|
2023-01-13 10:30:09 +03:00
|
|
|
}, [delay]);
|
|
|
|
}
|
2023-02-08 14:11:33 +03:00
|
|
|
|
|
|
|
export default useInterval;
|