Live2D

tsx格式防抖

定义:

import { useCallback, useEffect, useRef } from 'react';

export interface DebounceRefType {
  fn: Function;
  timer?: NodeJS.Timeout;
}

export type DebouncePropsType = [Function, number, any[]?];

const useDebounce = (...[fn, debounce, deps = []]: DebouncePropsType) => {
  const { current } = useRef<DebounceRefType>({ fn });

  useEffect(() => {
    current.fn = fn;
  }, [current, fn]);

  return useCallback(
    function (this: any, ...args: any[]) {
      if (current.timer) {
        clearTimeout(current.timer);
        delete current.timer;
      }

      current.timer = setTimeout(() => {
        current.fn.apply(this, args);
      }, debounce);
    },
    // eslint-disable-next-line
    [debounce, current, ...deps],
  );
};

export default useDebounce;

 使用:

import useDebounce from '@/common/useDebounce'

const handleGoStadiumList = useDebounce(() => {
   dosomething();
  }, timer);

 

posted @ 2024-02-21 19:02  喻佳文  阅读(6)  评论(0编辑  收藏  举报