spacedrive/interface/hooks/useRandomInterval.ts
Utku 6277c8cb5f
Command Palette (#2228)
* bring it back

* move into folder

* fix shortcuts colliding

* tags

* fix key capture problems

* add 2 more actions + locations to cmd

* fix search navigation issue W @nikec

* fix saerch input

* improve scrollbar look and text on lightheme + fix edge view search showing

* useShortcut

* add cmdp to keybinds page

* killer i18n extension for vscode

* some missing keys and localized cmdk

* in lists that can change - it's better to use the id rather than index to avoid extra re-renders

* Update CMDKLocations.tsx

---------

Co-authored-by: ameer2468 <33054370+ameer2468@users.noreply.github.com>
2024-03-26 13:05:46 +00:00

39 lines
1,021 B
TypeScript

import { useCallback, useEffect, useRef } from 'react';
// Utility helper for random number generation
const random = (min: number, max: number) => Math.floor(Math.random() * (max - min)) + min;
export const useRandomInterval = (
callback: () => void,
minDelay: number | null,
maxDelay: number | null
) => {
const timeoutId = useRef<number | null>(null);
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
const 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 = useCallback(function () {
window.clearTimeout(timeoutId.current!);
}, []);
return cancel;
};