笔记:防抖debounce和节流throttle

79 阅读1分钟

利用闭包、setTimeout实现

防抖debounce

  function debounce(func, delay) {
    let timer = null;
    return (...args) => {
      clearTimeout(timer); // 每次触发都清除上一个定时器
      timer = setTimeout(() => {
        func.apply(this, args); 
      }, delay);
    };
  }

节流throttle

  function throttle(func, delay) {
    let flag = true; // flag的含义可理解为是否可执行func
    return (...args) => {
      if (flag) {
        setTimeout(() => {
          func.apply(this, args);
          flag = true; // flag置true,下一次触发就可执行func
        }, delay);
      }
      flag = false; // 除了首次和setTimeout异步函数调用后,其他触发都是false
    };
  }

以上防抖和节流函数的触发指的是return的闭包(匿名)函数