Javascript防抖与节流示例详解
Javascript防抖与节流示例详解

防抖(debounce)
触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。(可以将防抖类比成电梯:第一个人进电梯之后,电梯会在5秒之后自动关闭电梯门,如果在这5秒内又有人进来了,那么电梯会重新等待5秒后再关门。)
应用场景:input搜索框,用户连续输入,等输入停下来或结束时再去触发搜索接口
实现:防抖主要是通过定时器实现
// fn 是事件处理程序,
// delay 是事件执行的延迟时间,单位:毫秒
function debounce(fn, delay){
let timer = null;
return function(...args) {
const _this = this;
// 每次触发事件 都把定时器清掉重新计时
clearTimeout(timer);
timer = setTimeout(function() {
// 执行事件处理程序
fn.call(_this, args);
}, delay);
}
}
示例
不使用防抖
使用防抖
节流(throttle)
当持续触发事件时,保证一定时间段内只调用一次事件处理函数。所以节流会稀释函数的执行频率
应用场景:按钮重复提交、滚动条事件、resize事件等高频监听事件
实现
1、使用时间戳实现
// fn 是事件处理程序
// delay 是事件执行的延迟时间,单位:毫秒
function throttle(fn, delay) {
// 定义初始时间(开始触发事件的时间)
let start = 0;
return function(...args) {
const _this = this;
// 获取当前时间戳
const current = Date.now();
// 判断当前时间与初始时间是否超过间隔
if (current - start >= delay) {
// 执行事件处理程序
fn.call(_this, args);
// 更新初始时间
start = current;
}
};
}
2、使用定时器实现
function throttle(fn, delay) {
let timer = null;
return function () {
const _this = this;
const args = arguments;
if (!timer) {
timer = setTimeout(function() {
// 执行事件处理程序
fn.call(_this, args);
// 事件执行完后把定时器清除掉,下次触发事件的时候再设置
timer = null;
}, delay);
}
};
}
示例
不使用节流
使用节流
What's Your Reaction?






