const { useState, useEffect, useRef } = React;
const useInterval = (callback, delay) => {
const saveCallback = useRef();
useEffect(() => {
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"));