useInterval的使用

回到文章>>

COPYHTML

<div id="app"></div>

COPYCSS

#app { font-size: 30px; } #app button { font-size: 24px; margin-right: 20px; }

COPYJAVASCRIPT

const { useState, useEffect, useRef } = React; const useInterval = (callback, delay) => { const saveCallback = useRef(); useEffect(() => { // 每次渲染后,保存新的回调到我们的 ref 里 saveCallback.current = callback; }); useEffect(() => { function tick() { saveCallback.current(); } if (delay !== null) { let id = setInterval(tick, delay); return () => clearInterval(id); } }, [delay]); }; const Home = () => { const [count, setCount] = useState(0); const [diff, setDiff] = useState(500); useInterval(() => { setCount(count + 1); }, diff); return ( <div> <p>count: {count}</p> <p>diff: {diff}ms</p> <p> <button onClick={() => setDiff(diff - 50)}>加快50ms</button> <button onClick={() => setDiff(diff + 50)}>减慢50ms</button> </p> </div> ); }; ReactDOM.render(<Home />, document.getElementById("app"));
新窗口打开