Created
July 12, 2022 04:02
-
-
Save AbePlays/b987de01b97ba99f8f1daf2a11e39b70 to your computer and use it in GitHub Desktop.
UseInterval
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 { 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