函数节流、函数防抖

函数防抖(debounce)

搜索事件
  • 短时间内多次触发同一事件,只执行最后一次,或者只执行最开始的一次,中间的不执行。(触发重新计时)
 function debounce(cb, wait = 1000) {
    let timer = null;
    return () => {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        cb();
        clearTimeout(timer);
        timer = null;
      }, wait);
    };
  }
  debounceButton.addEventListener(
    "click",
    debounce(function () {
      console.log("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 次… 。节流如字面意思,会稀释函数的执行频率。

function throttle(cb, wait = 1000) {
let timer = null;
let canRun = true;
return () => {
if (!canRun) {
return;
}
canRun = false;
cb(); // 需要立即执行时可以把回调放定时器外
timer = setTimeout(() => {
// cb(); // 计时后执行
clearTimeout(timer);
timer = null;
canRun = true;
}, wait);
};
}

throttleButton.addEventListener(
“click”,
throttle(function () {
console.log(“throttle”);
})
);

```js
// 微信小程序
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,
      });
    },
  },
});

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值