Skip to content

Instantly share code, notes, and snippets.

@gaperton
Created May 8, 2019 04:54
Show Gist options
  • Save gaperton/67ab4e2d165ce942c513a7ceb18c91fc to your computer and use it in GitHub Desktop.
Save gaperton/67ab4e2d165ce942c513a7ceb18c91fc to your computer and use it in GitHub Desktop.
function useThrottle( fun, timeout, changes = [] ){
// Create the mutable local ref to store timer.
const timer = useRef( null );
function cancel(){
if( timer.current ){
clearTimeout( timer.current );
timer.current = null;
}
}
// Cancel the timer when the given values change or the component will unmount.
useEffect( () => cancel, changes );
// Return the throttled version of the function.
return function( ...args ){
cancel();
// Save the timer to the ref, so it can be cancelled.
timer.current = setTimeout(()=>{
timer.current = null;
fun.apply( this, args );
}, timeout );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment