Created
February 10, 2020 16:00
-
-
Save NikaBuligini/7bcd13b5170bce20931ee4b03c946edd 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
| import React from 'react'; | |
| export function useInterval(callback, delay) { | |
| const savedCallback = React.useRef(); | |
| React.useEffect(() => { | |
| savedCallback.current = callback; | |
| }, [callback]); | |
| React.useEffect(() => { | |
| function tick() { | |
| savedCallback.current(); | |
| } | |
| if (delay !== null) { | |
| const id = setInterval(tick, delay); | |
| return () => clearInterval(id); | |
| } | |
| return undefined; | |
| }, [delay]); | |
| } | |
| export function useTimeout(callback, delay) { | |
| const savedCallback = React.useRef(); | |
| React.useEffect(() => { | |
| savedCallback.current = callback; | |
| }, [callback]); | |
| React.useEffect(() => { | |
| function onTimeout() { | |
| savedCallback.current(); | |
| } | |
| if (delay !== null) { | |
| const id = setTimeout(onTimeout, delay); | |
| return () => clearTimeout(id); | |
| } | |
| return undefined; | |
| }, [delay]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment