防抖和节流

//防抖 所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。 //推荐使用
timeId = null;
  debounce = (fn, time) => {
    if (this.timeId) {
      clearTimeout(this.timeId);
      this.timeId = null;
    }
    this.timeId = setTimeout(fn, time);
  };
  handleChange = (value) => {
    this.throttle(async () => {
      //   console.log(value);
      let res = await searchGoods({
        query: value,
      });
      // console.log(res);
      this.setState({
        goodsList: res.message || [],
      });
    }, 1000);
  };
 
//节流 所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数
 valid = true; // 标识上次事件是否已经完成
  throttle = (fn, timeout) => {
    // 上次事件已经执行完毕
    if (this.valid) {
      this.valid = false; // 设置定义器
      setTimeout(()=> {
        fn.call(this); // 执行回调函数
        this.valid = true;
      }, timeout);
    }
  };
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容