Skip to content

Instantly share code, notes, and snippets.

@madflanderz
Created January 13, 2020 09:37
Show Gist options
  • Save madflanderz/b9aa214cc98727e722161739598dbaa2 to your computer and use it in GitHub Desktop.
Save madflanderz/b9aa214cc98727e722161739598dbaa2 to your computer and use it in GitHub Desktop.
Effect to call a function after timeout
import { useEffect, useRef } from "react"
/**
* Runs a timeout after delay ms.
*
* @param callback function to execute
* @param delay delay time in ms
*
* Usage:
useTimeout(
() => console.log("executed"),
300
)
*/
function useTimeout(callback: () => void, delay?: number) {
const savedCallback = useRef<() => void | undefined>()
useEffect(() => {
savedCallback.current = callback
})
useEffect(() => {
function tick() {
savedCallback.current && savedCallback.current()
}
if (delay !== null) {
const id = setTimeout(tick, delay)
return () => clearTimeout(id)
}
}, [delay])
}
export default useTimeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment