Created
April 18, 2022 00:01
-
-
Save MarekZeman91/2df9eb11716bc6adc807651a62d77739 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 UseDebouncerCallback = (...args: any[]) => void; | |
export const useDebouncer = <T extends UseDebouncerCallback>( | |
callback: T, | |
delay: number, | |
runFirst?: boolean | |
): T & { clear: () => void } => { | |
const scope = useScope({ callback, delay, runFirst }); | |
const timeout = useRef<number>(0); | |
return useMemo(() => { | |
const debounce = (...args: T[]) => { | |
if (!timeout.current && scope.runFirst) { | |
scope.callback(...args); | |
} | |
window.clearTimeout(timeout.current); | |
timeout.current = window.setTimeout(() => { | |
timeout.current = 0; | |
scope.callback(...args); | |
}, scope.delay); | |
}; | |
debounce.clear = () => window.clearTimeout(timeout.current); | |
return debounce as T & { clear: () => void }; | |
}, [scope]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment