Last active
April 18, 2022 00:32
-
-
Save MarekZeman91/094d1e95e57583d6537e81bfb2a1fd70 to your computer and use it in GitHub Desktop.
This file contains 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
import { useMemo, useRef } from 'react'; | |
import { useScope } from './useScope'; | |
export type UseThrottlerCallback = (...args: any[]) => void; | |
export const useThrottler = <T extends UseThrottlerCallback>(callback: T, delay: number): T & { clear: () => void } => { | |
const scope = useScope({ callback, delay }); | |
const timeout = useRef<number>(0); | |
return useMemo(() => { | |
const throttler = (...args: T[]) => { | |
if (!timeout.current) scope.callback(...args); | |
window.clearTimeout(timeout.current); | |
timeout.current = window.setTimeout(() => (timeout.current = 0), scope.delay); | |
}; | |
throttler.clear = () => window.clearTimeout(timeout.current); | |
return throttler as T & { clear: () => void }; | |
}, [scope]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment