| 1 |
import { useEffect, useRef } from '@wordpress/element'; |
| 2 |
|
| 3 |
export const useRateLimitedCursor = (cb, intervalMs = 2000, deps = []) => { |
| 4 |
const lastAtRef = useRef(0); |
| 5 |
const timerRef = useRef(null); |
| 6 |
|
| 7 |
useEffect(() => { |
| 8 |
const schedule = () => { |
| 9 |
clearTimeout(timerRef.current); |
| 10 |
|
| 11 |
const now = Date.now(); |
| 12 |
const wait = Math.max(0, lastAtRef.current + intervalMs - now); |
| 13 |
|
| 14 |
const run = () => { |
| 15 |
lastAtRef.current = Date.now(); |
| 16 |
const hasMore = cb(); |
| 17 |
if (hasMore) schedule(); |
| 18 |
}; |
| 19 |
|
| 20 |
if (wait === 0) run(); |
| 21 |
else timerRef.current = setTimeout(run, wait); |
| 22 |
}; |
| 23 |
|
| 24 |
schedule(); |
| 25 |
|
| 26 |
return () => { |
| 27 |
clearTimeout(timerRef.current); |
| 28 |
timerRef.current = null; |
| 29 |
}; |
| 30 |
}, [cb, intervalMs, ...deps]); |
| 31 |
}; |
| 32 |
|