Created
January 13, 2020 09:37
-
-
Save madflanderz/b9aa214cc98727e722161739598dbaa2 to your computer and use it in GitHub Desktop.
Effect to call a function after timeout
This file contains hidden or 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
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