Last active
April 18, 2019 15:02
-
-
Save erkobridee/74c706b13cbf27a75d91102c49077b77 to your computer and use it in GitHub Desktop.
This file contains 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 * as React from 'react'; | |
export type TFunction = (...args: any[]) => any; | |
/** | |
* safe way to use window.setInterval using a hook to handle it | |
* | |
* @param {TFunction} callback to be executed on each interval | |
* @param {number} delay time between the executions | |
* @param {boolean} autorun flag that says if should start running right after call the hook - default true | |
* | |
* @return {[TFunction, TFunction]} start and stop functions | |
*/ | |
export function useInterval(callback: TFunction, delay: number, autorun: boolean = true): [TFunction, TFunction] { | |
const saveCallback = React.useRef<TFunction>(callback); | |
const intervalRef = React.useRef<number | undefined>(undefined); | |
const startInterval = React.useCallback(() => { | |
if (intervalRef.current || !Number(delay) || delay < 0) { | |
return; | |
} | |
const tick = () => { | |
saveCallback.current(); | |
intervalRef.current = undefined; | |
}; | |
intervalRef.current = window.setInterval(tick, delay); | |
}, []); | |
const stopInterval = React.useCallback(() => { | |
if (!intervalRef.current) { | |
return; | |
} | |
window.clearInterval(intervalRef.current); | |
intervalRef.current = undefined; | |
}, []); | |
React.useEffect(() => { | |
saveCallback.current = callback; | |
}, [callback]); | |
React.useEffect(() => { | |
if (autorun) { | |
stopInterval(); | |
startInterval(); | |
} | |
return () => stopInterval(); | |
}, [delay, autorun]); | |
return [startInterval, stopInterval]; | |
} | |
export default useInterval; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment