Skip to content

Instantly share code, notes, and snippets.

@erkobridee erkobridee/useInterval.ts
Last active Apr 18, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.