Skip to content

useCommon 对于通用的业务逻辑封装

上次更新 2024年10月30日星期三 7:57:13 字数 0 字 时长 0 分钟

js
const useCommon = () => {
  /**
   * @description 防抖函数
   * 定义:确保一个函数在最后一次触发后的设定时间间隔(例如 500ms)后再执行。
   * 行为:在设定的时间间隔内,如果函数被再次触发,则重新计时,直到最后一次触发后的设定时间间隔结束后才执行。
   * 示例:在 2 秒内频繁触发函数,防抖函数会在最后一次触发后的 500ms 执行一次。
   * 通俗理解:一定时间 连续触发函数 重新计时
   * @param {Function} func 函数
   * @param {Number} wait 延迟执行毫秒数
   */
  const debounce = (func, wait) => {
    let timeout;
    return function (...args) {
      const context = this;
      clearTimeout(timeout);
      timeout = setTimeout(() => func.apply(context, args), wait);
    };
  };

  /**
   * @description 节流函数
   * 定义:确保一个函数在一定时间间隔内最多只执行一次。
   * 行为:在设定的时间间隔(例如 500ms)内,无论触发多少次,函数最多只执行一次。
   * 示例:在 2 秒内频繁触发函数,节流函数会在第 0.5 秒、1 秒、1.5 秒和 2 秒各执行一次。
   * 通俗理解:一定时间 触发一次
   * @param {Function} func 函数
   * @param {Number} wait 延迟执行毫秒数
   */
  const throttle = (func, wait) => {
    let previous = Date.now();
    return function (...args) {
      let now = Date.now();
      let context = this;
      if (now - previous > wait) {
        previous = now;
        func.apply(context, args);
      }
    };
  };

  return { debounce, throttle };
};