Created
May 8, 2019 04:54
-
-
Save gaperton/67ab4e2d165ce942c513a7ceb18c91fc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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