Last active
November 26, 2018 10:57
-
-
Save JamieDixon/d21a6d66ca9b6fbe4244a9592fc91f10 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
const useThrottle = (fn, wait) => { | |
const throttledRef = useRef(fn); | |
const lastCallRef = useRef({ fn: () => {}, args: null }); | |
useEffect( | |
() => { | |
let isThrottling = false; | |
throttledRef.current = (...args) => { | |
if (isThrottling) { | |
lastCallRef.current = { | |
fn, | |
args | |
}; | |
return; | |
} | |
fn(...args); | |
isThrottling = true; | |
setTimeout(() => { | |
isThrottling = false; | |
const { fn, args } = lastCallRef.current; | |
fn(...args); | |
}, wait); | |
}; | |
}, | |
[wait] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment