Skip to content

Commit

Permalink
Added useTimeout hook
Browse files Browse the repository at this point in the history
  • Loading branch information
bgonp committed Jan 30, 2021
1 parent fbf36ca commit 1fc731c
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "bgon-custom-hooks",
"version": "0.3.0",
"version": "0.4.0",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ if (typeof window === "undefined") {
}

export { useLocalStorage } from "./useLocalStorage";
export { useTimeout } from "./useTimeout";
37 changes: 37 additions & 0 deletions src/useTimeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useCallback, useEffect, useState } from 'react'

type SetTimeoutType = (callback: () => void, milliseconds: number) => void

type ClearTimeoutType = () => void

type UseTimeoutType = {
setTimeout: SetTimeoutType
clearTimeout: ClearTimeoutType
}

export const useTimeout = (): UseTimeoutType => {
const [timeout, setTimeoutValue] = useState<number | null>(null)

const setTimeout = useCallback<SetTimeoutType>((callback, milliseconds) => {
setTimeoutValue((prevTimeout) => {
if (prevTimeout) window.clearTimeout(prevTimeout)
return window.setInterval(callback, milliseconds)
})
}, [])

const clearTimeout = useCallback<ClearTimeoutType>(() => {
setTimeoutValue(null)
}, [])

useEffect(() => {
const prevTimeout = timeout
return () => {
if (prevTimeout) window.clearTimeout(prevTimeout)
}
}, [timeout])

return {
setTimeout,
clearTimeout,
}
}

0 comments on commit 1fc731c

Please sign in to comment.