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