两者都是为了避免在一个连续的行为中触发多次事件响应;
函数节流
函数节流是指连续的事件中,按照一定的时间间隔去执行一次事件响应,常用场景:
- 滚动条滚动事件
window.scroll; DOM的拖拽事件mousemove;
实现代码:
// 闭包
function throttle(fn, wait) {
let timer = null;
return function (e) {
const context = this;
const args = arguments;
if (!timer) {
timer = setTimeout(() => {
timer = null;
// 传递参数,如事件对象e;修改this指向;
fn.apply(context, args);
}, wait);
}
};
}
调用方法:
// 滚动条滚动事件1秒执行一次
window.onscroll = throttle((e) => {
console.log(e);
}, 1000)
函数防抖
函数节流是指连续的事件中,只执行最后一次事件响应,常用场景:
- 输入框输入后做
ajax查询请求; - 窗口
resize事件后重新计算布局; - 快速重复点击同一个按钮;
实现代码:
function debounce(fn, wait) {
let timer = null;
return function() {
const context = this;
const args = arguments;
timer && clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, wait);
}
}
调用方法:
// 输入框输入后做`ajax`查询请求
input.onchange = debounce((e) => {
console.log(e);
}, 1000)