对防抖、节流的理解-按钮为例

115 阅读1分钟

<el-button type="primary" @click.native="download1">下载截流</el-button> <el-button type="primary" @click.native="download2">下载防抖</el-button>

//节流
const throttle = function (fn, delay) {
  let timer = null;
  let start = Date.now();
  console.log("throttle");
  return () => {
    let that = this;
    let arg = arguments;
    let now = Date.now();
    let remainTime = delay - (now - start);
    if (remainTime <= 0) {
      console.log("1");
      fn.apply(that, arg);
      start = Date.now();
    } else {
      console.log("2");
      clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(that, arg);
      }, remainTime);
    }
  };
};
//防抖
const decounce = function (fn, delay, immediate) {
  let timer = null;
  console.log("fn", this);
  return function () {
    const that = this;
    const arg = arguments;
    console.log("arg");
    if (timer) {
      clearTimeout(timer);
    }
    if (immediate) {
      const callNow = !timer;
      timer = setTimeout(function () {
        timer = null;
      }, delay);
      if (callNow) {
        console.log("callNow");
        fn.apply(that, arg);
      }
    } else {
      console.log("else");
      timer = setTimeout(function () {
        fn.apply(that, arg);
      }, delay);
      console.log("timer", timer);
    }
  };
};
export default {
  data() {
    return {};
  },
  methods: {
    download1: throttle(() => {
      console.log("123");
    }, 3000),
    download2: decounce(
      () => {
        console.log("456");
      },
      3000,
      true
    ),
  },
};
</script>