Last active
August 7, 2021 19:19
-
-
Save fackux/027b20734dec7bba39e5f7c403d3ace1 to your computer and use it in GitHub Desktop.
JS Utils
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
export const random = (min, max) => Math.floor(Math.random() * (max - min)) + min; | |
/* https://www.joshwcomeau.com/snippets/react-hooks/use-random-interval */ | |
export const useRandomInterval = (callback, minDelay, maxDelay) => { | |
const timeoutId = React.useRef(null); | |
const savedCallback = React.useRef(callback); | |
React.useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
React.useEffect(() => { | |
let isEnabled = | |
typeof minDelay === 'number' && typeof maxDelay === 'number'; | |
if (isEnabled) { | |
const handleTick = () => { | |
const nextTickAt = random(minDelay, maxDelay); | |
timeoutId.current = window.setTimeout(() => { | |
savedCallback.current(); | |
handleTick(); | |
}, nextTickAt); | |
}; | |
handleTick(); | |
} | |
return () => window.clearTimeout(timeoutId.current); | |
}, [minDelay, maxDelay]); | |
const cancel = React.useCallback(function () { | |
window.clearTimeout(timeoutId.current); | |
}, []); | |
return cancel; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment