函数防抖(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,
});
},
},
});