1、概念
防抖:指在事件被触发的n秒后再执行回调,如果在这n秒内事件又被触发,则重新计时。
节流:指在单位时间内,只能有一次触发事件的回调函数执行,如果在同一单位时间内事件再次被触发,则不生效。
2、应用场景
防抖:表单验证需要服务端配合,如input输入用户名,需要在输入过程中查询该用户是否注册过,连续的输入事件只有最后一次执行请求操作。
节流:检测浏览器的resize事件,根据resize的变化需要实时计算的大小和位置的场景。连续的事件调用,会变成每单位时间只触发一次回调。
3、函数实现
函数防抖的实现 ⬇
function debounce(fn, wait) {
let timer = null;
return function() {
let context = this,
args = [...arguments];
// 如果此时存在定时器的话,则取消之前的定时器重新记时
if (timer) {
clearTimeout(timer);
timer = null;
}
// 设置定时器,使事件间隔指定事件后执行
timer = setTimeout(() => {
fn.apply(context, args);
}, wait);
};
}
函数节流的实现 ⬇
// 时间戳版
function throttle(fn, delay) {
let preTime = Date.now();
return function() {
let context = this,
args = [...arguments],
nowTime = Date.now();
// 如果两次时间间隔超过了指定时间,则执行函数。
if (nowTime - preTime >= delay) {
preTime = Date.now();
return fn.apply(context, args);
}
};
}
// 定时器版
function throttle (fun, wait){
let timeout = null;
return function(){
let context = this,
args = [...arguments];
if(!timeout){
timeout = setTimeout(() => {
fun.apply(context, args);
timeout = null ;
}, wait);
}
}
}