-
Notifications
You must be signed in to change notification settings - Fork 3
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
Viktor Riabkov
committed
Feb 1, 2024
1 parent
09f9796
commit f1e3e9f
Showing
2 changed files
with
30 additions
and
0 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 |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { useCallback, useRef } from "react" | ||
|
||
type SetTimerProps = { | ||
callback: () => void | ||
delay: number | ||
} | ||
|
||
export const useTimer = () => { | ||
const timerRef = useRef<number | undefined>(undefined) | ||
|
||
// this resets the timer if it exists. | ||
const resetTimer = useCallback(() => { | ||
if (timerRef) window.clearTimeout(timerRef.current) | ||
}, [timerRef]) | ||
|
||
const setTimer = useCallback( | ||
(props: SetTimerProps) => { | ||
timerRef.current = window.setTimeout(() => { | ||
// clears any pending timer. | ||
resetTimer() | ||
|
||
props.callback() | ||
}, props.delay) | ||
}, | ||
[resetTimer], | ||
) | ||
|
||
return { setTimer, resetTimer } | ||
} |