防抖|节流

48 阅读1分钟
  • 防抖: 间隔一定时间不触发动作才触发一次事件
  • 节流: 间隔一定时间才触发一次时间

// 节流
/* const throttle = (fn, delay) => {
      let flag = true;
      return () => {
        if (flag) {
          setTimeout(() => {
            // fn.apply(this, args);
            fn.call(this);
            flag = true;
          }, delay);
          flag = false;
        }
      };
    }; */

const throttle = (fn, delay) => {
      let t = 0;
      return () => {
        const now = Date.now();
        if (now - t >= delay) {
          fn.call(this);
          t = now;
        }
      };
    };
    window.onscroll = throttle(() => {
      console.log("滚动");
    }, 1000);
    
    // 防抖
    const debounce = (fn, delay) => {
      let timer = null;
      return () => {
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.call(this);
          timer = null;
        }, delay);
      };
    };
    this.$refs.input.addEventListener(
      "input",
      debounce(() => {
        console.log("input");
      }, 1000)
    );