函数防抖(debounce)
理解
在动作触发完n秒后执行事件,指定时间间隔n秒内如果多次触发,则从最后一次触发后重新计时
适用场景
- 响应式布局resize事件
- 输入文字停止后校验,keyup事件
代码实现
export function debounce(func, wait) {
let timer;
return function() {
let context = this,
args = arguments;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
func.apply(context, args);
}, wait);
}
}
函数节流(throttle)
理解
预设一个时间周期,只有当上一次执行该事件与当前触发时间的间隔
大于预设周期时,才执行该事件
适用场景
- click事件,防止用户不停的快速点击,减少事件触发频率
- 发送ajax请求,降低请求频率
代码实现
export function throttle(func, wait) {
let lastTime;
return function() {
let context = this,
args = arguments;
let nowTime = new Date().getTime()
let callNow = nowTime - lastTime > wait || !lastTime;
if (callNow) {
lastTime = nowTime
func.apply(context, args);
}
}
}
本文使用 mdnice 排版