Skip to content

Instantly share code, notes, and snippets.

@AbePlays
Created July 12, 2022 04:02
Show Gist options
  • Save AbePlays/b987de01b97ba99f8f1daf2a11e39b70 to your computer and use it in GitHub Desktop.
Save AbePlays/b987de01b97ba99f8f1daf2a11e39b70 to your computer and use it in GitHub Desktop.
UseInterval
import { useEffect, useRef, useState } from 'react';
interface UseIntervalProps {
fn: () => void;
interval: number;
}
interface UseIntervalReturn {
active: boolean;
start: () => void;
stop: () => void;
toggle: () => void;
}
export default function useInterval(props: UseIntervalProps): UseIntervalReturn {
const { fn, interval } = props;
const fnRef = useRef<() => void>();
const intervalRef = useRef<number>();
const [active, setActive] = useState(false);
useEffect(() => {
fnRef.current = fn;
}, [fn]);
function start() {
setActive((old) => {
if (!old) {
intervalRef.current = window.setInterval(fnRef.current, interval);
}
return true;
});
}
function stop() {
setActive(false);
window.clearInterval(intervalRef.current);
}
function toggle() {
if (active) {
stop();
} else {
start();
}
}
return { active, start, stop, toggle };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment