前端面试题:手写防抖 节流(送分)

537 阅读1分钟

手写节流函数 防抖函数

节流函数

节流函数的精髓在于降低事件的触发频率

 const throttle = (fn, delay) => {
      let timer = null;
      return function () {
        // 等到定时器执行完再重新赋值一个定时器
        // 定时器还在执行期间不绑定,从而降低了触发频率
        if (timer === null) {
          timer = setTimeout(() => {
            fn.apply(this, arguments);
            timer = null;
          }, delay);
        }
      };
    };

防抖函数

防抖函数的精髓在于将事件的多次触发变成一次触发

const debounce = (fn, delay) => {
      let timer = null;
      return function () {
        if (timer !== null) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          // 因为这里有this,arguments,所以return不能写成箭头函数
          fn.apply(this, arguments);
          timer = null;
        }, delay);
      };
    };