Skip to content

Instantly share code, notes, and snippets.

@fackux
Last active August 7, 2021 19:19
Show Gist options
  • Save fackux/027b20734dec7bba39e5f7c403d3ace1 to your computer and use it in GitHub Desktop.
Save fackux/027b20734dec7bba39e5f7c403d3ace1 to your computer and use it in GitHub Desktop.
JS Utils
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