Skip to content

Instantly share code, notes, and snippets.

@gaurangrshah
Created July 9, 2021 21:58
Show Gist options
  • Save gaurangrshah/decbd73bb92f7fd7d6e99f650421ffd4 to your computer and use it in GitHub Desktop.
Save gaurangrshah/decbd73bb92f7fd7d6e99f650421ffd4 to your computer and use it in GitHub Desktop.
function useThrottle(value, interval = 500) {
const [throttledValue, setThrottledValue] = useState(value);
const lastExecuted = useRef(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