Last active
September 21, 2019 05:17
-
-
Save andycarrell/562a82ae9d666b1050428636f190a81b to your computer and use it in GitHub Desktop.
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
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 | |
} |
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
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