Skip to content

Instantly share code, notes, and snippets.

@krystalcampioni
Created July 17, 2022 01:21
Show Gist options
  • Save krystalcampioni/e7b0bc529f5d3e4b90d8b3d05bcc34c5 to your computer and use it in GitHub Desktop.
Save krystalcampioni/e7b0bc529f5d3e4b90d8b3d05bcc34c5 to your computer and use it in GitHub Desktop.
function useThrottle<T>(value: T, interval = 500): T {
const [throttledValue, setThrottledValue] = useState<T>(value);
const lastExecuted = useRef<number>(Date.now());
useEffect(() => {
if (Date.now() >= lastExecuted.current + interval) {
lastExecuted.current = Date.now();
setThrottledValue(value);
} else {
const timerId = setTimeout(() => {
lastExecuted.current = Date.now();
setThrottledValue(value);
}, interval);
return () => clearTimeout(timerId);
}
}, [value, interval]);
return throttledValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment