-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1d5cd10
commit 26cab31
Showing
3 changed files
with
17 additions
and
4 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,27 @@ | ||
import { useCallback, useRef } from 'react'; | ||
import useUpdateEffect from './useUpdateEffect'; | ||
|
||
|
||
const useDebounce = (fn: () => any, ms: number = 0, args: any[] = []) => { | ||
|
||
const timer = useRef<number>(); | ||
|
||
useUpdateEffect(() => { | ||
const handle = setTimeout(fn.bind(null, args), ms); | ||
|
||
timer.current = window.setTimeout(fn.bind(null, args), ms); | ||
return () => { | ||
// if args change then clear timeout | ||
clearTimeout(handle); | ||
window.clearTimeout(timer.current); | ||
}; | ||
}, args); | ||
|
||
const cancel = useCallback(() => { | ||
if (timer.current) { | ||
window.clearTimeout(timer.current); | ||
} | ||
}, []); | ||
|
||
return { cancel }; | ||
}; | ||
|
||
export default useDebounce; |
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