A
Size: a a a
A
T
A
T
p
const useRecursiveTimeout = (callback, delay = 1000) => {
const savedCallback = useRef()
useEffect(() => {
savedCallback.current = callback
})
useEffect(() => {
const tick = () => {
const ret = savedCallback?.current()
if (!ret) {
queueMicrotask(() => setTimeout(tick, delay))
}
}
const timer = setTimeout(tick, delay)
return () => clearTimeout(timer)
}, [delay])
};p
if (typeof window.queueMicrotask !== "function") {
window.queueMicrotask = function (callback) {
Promise.resolve()
.then(callback)
.catch(e => setTimeout(() => { throw e; })); // report exceptions
};
}G
G
G
В
p
В
p
const Counter = () => {
const [count, setCount] = useState(0)
useRecursiveTimeout(() => setCount(count + 1), 1000)
return (
<div>
<button onClick={() => setCount(count - 1)}>-</button>
<span>{count}</span>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
)
};p
p
В
p
В
В