微信小程序之函数节流、函数防抖

函数防抖(debounce)

搜索事件

  • 短时间内多次触发同一事件,只执行最后一次,或者只执行最开始的一次,中间的不执行。(触发重新计时)
// 微信小程序
module.exports = Behavior({
    
    
  data: {
    
    
    canRun: true,
    timer: null,
  },
  methods: {
    
    
    debounce(callback, wait = 800) {
    
    
      const {
    
     canRun, timer } = this.data;
      if (canRun) {
    
    
        callback();
        this.data.canRun = false;
      }
      timer && clearInterval(this.data.timer);
      this.data.timer = setInterval(() => {
    
    
        this.data.canRun = true;
      }, wait);
    },
  },
});

函数节流(throttle) — 稀释 单位: 次/n秒

点击事件

  • 指连续触发事件但是在 n 秒中只执行一次函数。即 2n 秒内执行 2 次… 。节流如字面意思,会稀释函数的执行频率。
// 微信小程序
module.exports = Behavior({
    
    
  data: {
    
    
    timer: null,
  },
  methods: {
    
    
    throttle(callback, wait = 500) {
    
    
      let {
    
     timer } = this.data;
      if (timer) clearTimeout(timer);
      timer = setTimeout(function () {
    
    
        callback();
      }, wait);
      this.setData({
    
    
        timer,
      });
    },
  },
});

猜你喜欢

转载自blog.csdn.net/qq_36303110/article/details/110798309