Relay firehose browser tools: https://compare.hose.cam
at main 34 lines 942 B view raw
1import { useCallback } from 'react'; 2 3export function asyncThrottle(minT, callback, followUp) { 4 let timer = null; 5 let lastArgs = null; 6 7 let throttleId = 0; 8 9 function throttled(...args) { 10 // always make sure our callback args are fresh 11 lastArgs = args; 12 13 // early exit if we're waiting for the throttle still 14 if (timer !== null) { 15 return; 16 } 17 18 // otherwise we're starting a timer. make sure we know who we are. 19 let myThrottle = ++throttleId; 20 // we immediately get a new timer id 21 timer = setTimeout(async () => { 22 // make sure we synchronously clear this so next throttle isn't lost 23 timer = null; 24 // *then* we can start the actual callback 25 let res = await callback(...lastArgs); 26 // but since we awaited the callback, it's now possible to be stale, so check 27 if (myThrottle === throttleId) { 28 followUp(res); 29 } 30 }, minT); 31 32 } 33 return throttled; 34}