1.防抖(Debounce)
定义:防抖的原理是在事件触发后,等待一定时间,如果在这段时间内没有再次触发事件,则执行回调函数。如果事件再次触发,则重新计时。简单来说,防抖会等用户停止操作后再执行函数。
应用场景:防抖适用于用户输入类操作,或者需要在用户停止一段时间操作后才执行的场景,比如搜索框的实时查询、窗口大小调整等。
// 防抖函数的封装
function debounce(fn, delay) {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer); // 每次触发事件时,清除上一次的定时器
timer = setTimeout(() => {
fn.apply(this, args); // 一段时间后才执行
}, delay);
};
}
示例:防抖用于搜索框输入联想
<input type="text" bindinput="onInput" placeholder="输入搜索关键词">
Page({
onInput: debounce(function (e) {
console.log('搜索关键词:', e.detail.value);
}, 500)
});
2.节流(Throttle)
定义:节流的原理是在一定时间间隔内只允许执行一次回调函数。如果在这个时间段内多次触发事件,则只有第一次事件会被响应,之后的事件会被忽略,直到时间间隔结束后,才可以响应下一个事件。
应用场景:当用户频繁点击按钮时,如果不加限制,可能会导致重复请求。通过节流机制,可以控制按钮点击的频率,从而避免请求多次发送。
// 节流函数的封装
function throttle(fn, interval) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= interval) {
lastCall = now;
fn.apply(this, args); // 每隔 interval 时间执行一次
}
};
}
示例:节流重复提交表单
<!-- debounce-button.wxml -->
<view class="button" bindtap="handleTap">{{ text }}</view>
// throttle-button.js
Component({
properties: {
text: {
type: String,
value: '节流按钮'
},
throttleTime: {
type: Number,
value: 500
}
},
methods: {
handleTap: throttle(function () {
this.triggerEvent('click');
}, this.properties.throttleTime)
}
});