react-hook设定定时器的方法

    const useInterval = (callback, delay) => {
        const savedCallback = useRef();

        // 保存新回调
        useEffect(() => {
            savedCallback.current = callback;
        });

        // 建立 interval
        useEffect(() => {
            function tick() {
                savedCallback.current();
            }
            if (delay !== null) {
                let id = setInterval(tick, delay);
                return () => clearInterval(id);
            }
        }, [delay]);
    }

  

posted @ 2019-09-18 11:39  kimingw  阅读(4378)  评论(0编辑  收藏  举报