Skip to content

Commit

Permalink
feat: useTimer hook
Browse files Browse the repository at this point in the history
  • Loading branch information
Viktor Riabkov committed Feb 1, 2024
1 parent 09f9796 commit f1e3e9f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/shared/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from "./helpers"
export * from "./eventEmitter"
export * from "./dictionary.map"
export * from "./mixpanel"
export * from "./useTimer"
29 changes: 29 additions & 0 deletions src/shared/utils/useTimer.ts
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 }
}

0 comments on commit f1e3e9f

Please sign in to comment.