Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Last active April 18, 2019 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erkobridee/74c706b13cbf27a75d91102c49077b77 to your computer and use it in GitHub Desktop.
Save erkobridee/74c706b13cbf27a75d91102c49077b77 to your computer and use it in GitHub Desktop.
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