• 防抖debounce(事件被触发n秒后执行回调函数, 如果在这n秒内又被触发, 则重新计时)

场景

  • 按钮防止重复点击
  • 搜索框连续输入的情况等输入停止后再搜索
  • 浏览器窗口大小变化仅需要触发一次事件
//debounce antvis/utils
function debounce(func: Function, wait?: number, immediate?: boolean) {
  let timeout; 
 
  return function () {
    const context = this,
      args = arguments;
    const later = function () {
      timeout = null;
      if (!immediate) {
        func.apply(context, args);
      }
    };
    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) {
      func.apply(context, args);
    }
  };
}
 
export default debounce;
  • 节流
//throttle
let last = 0;
 
function throttle(fn, gapTime, ...arg) {
    let nowTime = Date.now();
    if(nowTime - last > gapTime) {
        fn.apply(this, ...arg);
        last = nowTime;
    }
}
// throttle by requestanimation
export function throttleByRaf(cb: (...args: any[]) => void) {
  let timer = 0;
 
  const throttle = (...args: any[]): void => {
    if (timer) {
      cancelAnimationFrame(timer);
    }
    timer = requestAnimationFrame(() => {
      cb(...args);
      timer = 0;
    });
  };
 
  throttle.cancel = () => {
    cancelAnimationFrame(timer);
    timer = 0;
  };
 
  return throttle;
}