Skip to content

Instantly share code, notes, and snippets.

@andycarrell
Last active September 21, 2019 05:17
Show Gist options
  • Save andycarrell/562a82ae9d666b1050428636f190a81b to your computer and use it in GitHub Desktop.
Save andycarrell/562a82ae9d666b1050428636f190a81b to your computer and use it in GitHub Desktop.
function useSetTimeout(callback, delay) {
const savedCallback = useRef()
const savedTimeout = useRef(() => {})
function runTimeout() {
savedTimeout.current()
}
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
function out() {
savedCallback.current()
}
if (delay !== null) {
let id = null
savedTimeout.current = () => {
id = setTimeout(out, delay)
}
return () => clearTimeout(id)
}
savedTimeout.current = () => {}
return () => {}
}, [delay])
return runTimeout
}
function useTimeout() {
const [delay, setDelay] = useState(null)
const savedCallback = useRef()
function runTimeout(callback, d) {
savedCallback.current = callback
setDelay(d)
}
useEffect(() => {
function out() {
savedCallback.current()
}
if (delay !== null) {
const id = setTimeout(out, delay)
return () => {
clearTimeout(id)
setDelay(null)
}
}
}, [delay])
return runTimeout
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment