mirror of
https://github.com/usememos/memos.git
synced 2025-06-05 22:09:59 +02:00
chore: debounce search text input (#943)
* chore: debounce search text input * chore: update
This commit is contained in:
40
web/src/hooks/useTimeoutFn.ts
Normal file
40
web/src/hooks/useTimeoutFn.ts
Normal file
@ -0,0 +1,40 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
|
||||
export type UseTimeoutFnReturn = [() => boolean | null, () => void, () => void];
|
||||
|
||||
export default function useTimeoutFn(fn: () => any, ms = 0): UseTimeoutFnReturn {
|
||||
const ready = useRef<boolean | null>(false);
|
||||
const timeout = useRef<ReturnType<typeof setTimeout>>();
|
||||
const callback = useRef(fn);
|
||||
|
||||
const isReady = useCallback(() => ready.current, []);
|
||||
|
||||
const set = useCallback(() => {
|
||||
ready.current = false;
|
||||
timeout.current && clearTimeout(timeout.current);
|
||||
|
||||
timeout.current = setTimeout(() => {
|
||||
ready.current = true;
|
||||
callback.current();
|
||||
}, ms);
|
||||
}, [ms]);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
ready.current = null;
|
||||
timeout.current && clearTimeout(timeout.current);
|
||||
}, []);
|
||||
|
||||
// update ref when function changes
|
||||
useEffect(() => {
|
||||
callback.current = fn;
|
||||
}, [fn]);
|
||||
|
||||
// set on mount, clear on unmount
|
||||
useEffect(() => {
|
||||
set();
|
||||
|
||||
return clear;
|
||||
}, [ms]);
|
||||
|
||||
return [isReady, clear, set];
|
||||
}
|
Reference in New Issue
Block a user