import { useEffect, useRef } from "react";

/**
 * 计时器
 */
export default function useInterval(fn, delay, immediate) {
  const callbackRef = useRef()
  callbackRef.current = fn;

  useEffect(() => {
    if (delay === undefined || delay === null) return;

    if (immediate) {
      callbackRef.current()
    }

    const ticker = setInterval(() => callbackRef.current(), delay)
    return () => clearInterval(ticker)
  }, [delay, immediate])
}
