Obtenga anti-vibración y estrangulamiento

Anti vibración:

/* ------------------- 函数去抖-debounce ------------------- */
/**
   * @param  {Function} fn         [回调函数]
   * @param  {[Time]}   delayTime  [延迟时间(ms)]
   * @param  {Boolean}  isImediate [是否需要立即调用]
   * @param  {[type]}   args       [回调函数传入参数]
  */
export function fnDebounce() {
    
    
  const fnObject = {
    
    };
  let timer;

  return (fn, delayTime, isImediate, args) => {
    
    
    // 设置定时器方法
    const setTimer = () => {
    
    
      timer = setTimeout(() => {
    
    
        fn(args);
        // 清除定时器
        clearTimeout(timer);
        delete (fnObject[fn]);
      }, delayTime);

      fnObject[fn] = {
    
    
        delayTime,
        timer,
      };
    };

    // 立即调用
    if (!delayTime || isImediate) return fn(args);

    // 判断函数是否已经在调用中
    if (fnObject[fn]) {
    
    
      clearTimeout(timer);
      // 定时器
      setTimer(fn, delayTime, args);
    } else {
    
    
      // 定时器
      setTimer(fn, delayTime, args);
    }
  };
}

Estrangulamiento:

/* ------------------- 函数节流-throttle ------------------- */
/**
   * @param  {Function} fn         [回调函数]
   * @param  {[Time]}   delayTime  [延迟时间(ms)]
   * @param  {Boolean}  isImediate [是否需要立即调用]
   * @param  {[type]}   args       [回调函数传入参数]
  */
export function fnThrottle() {
    
    
  const fnObject = {
    
    };

  return (fn, delayTime, IsImediate, args) => {
    
    
    // 立即调用
    if (!delayTime || IsImediate) {
    
    
      return fn(args);
    }
    // 判断函数是否已经在调用中
    if (!fnObject[fn]) {
    
    
      // 定时器
      const timer = setTimeout(() => {
    
    
        fn(args);
        // 清除定时器
        clearTimeout(timer);
        delete (fnObject[fn]);
      }, delayTime);

      fnObject[fn] = {
    
    
        status: 'waitToRun',
        delayTime,
        timer,
      };
    }
  };
}

Supongo que te gusta

Origin blog.csdn.net/Chennfengg222/article/details/112985345
Recomendado
Clasificación