9433cfb9创建于 2025年12月31日历史提交
/**
 * 防抖函数
 *  防抖示例:输入框搜索
	const search = debounce((keyword: string) => {
	  console.log('执行搜索:', keyword);
	  // 这里写接口请求逻辑
	}, 500);
 * @param func 要防抖的函数
 * @param wait 防抖延迟时间(ms)
 * @returns 防抖后的函数
 */
export const debounce = (func: any, wait: number): any => {
  // UTS 中 setTimeout 返回 number 类型
  let timeout: number | null = null;

  return function (this: any, ...args: any[]) {
    if (timeout !== null) {
      clearTimeout(timeout);
    }
    // 重新设置定时器,绑定正确上下文和参数
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
};

/**
 * 节流函数
 *  节流示例:页面滚动
	const handleScroll = throttle(() => {
	  console.log('滚动中,节流执行');
	  // 这里写滚动处理逻辑
	}, 200);
 * @param fn 要节流的函数
 * @param wait 节流间隔时间(ms)
 * @returns 节流后的函数
 */
export const throttle = (fn: any, wait: number): any => {
  let canRun = true; // 节流开关

  return function (this: any, ...args: any[]) {
    if (!canRun) return;

    canRun = false;
    setTimeout(() => {
      fn.apply(this, args);
      canRun = true;
    }, wait);
  };
};