什么是防抖和节流有什么区别?
1 是什么
本质上是优化⾼频率执⾏代码的⼀种⼿段
如:浏览器的 resize 、 scroll 、 keypress 、 mousemove 等事件在触发时,会不断地调⽤绑定在事件上的回调函数,极⼤地浪费资源,降低前端性能
为了优化体验,需要对这类事件进⾏调⽤次数的限制,对此我们就可以采⽤ 防抖(debounce) 和 节流(throttle) 的⽅式来减少调⽤频率
1.1 定义
- 节流: n 秒内只运⾏⼀次,若在 n 秒内重复触发,只有⼀次⽣效
- 防抖: n 秒后在执⾏该事件,若在 n 秒内被重复触发,则重新计时
⼀个经典的⽐喻:
想象每天上班⼤厦底下的电梯。把电梯完成⼀次运送,类⽐为⼀次函数的执⾏和响应
假设电梯有两种运⾏策略 debounce 和 throttle ,超时设定为15秒,不考虑容量限制
电梯第⼀个⼈进来后,15秒后准时运送⼀次,这是节流
电梯第⼀个⼈进来后,等待15秒。如果过程中⼜有⼈进来,15秒等待重新计时,直到15秒后开始运送,这是防抖
2 代码实现
2.1 节流
完成节流可以使⽤时间戳与定时器的写法
使⽤时间戳写法,事件会⽴即执⾏,停⽌触发后没有办法再次执⾏
function throttled1(fn, delay = 500) {
let oldtime = Date.now()
return function (...args) {
let newtime = Date.now()
if (newtime - oldtime >= delay) {
fn.apply(null, args)
oldtime = Date.now()
}
}
}
使⽤定时器写法, delay 毫秒后第⼀次执⾏,第⼆次事件停⽌触发后依然会再⼀次执⾏
function throttled2(fn, delay = 500) {
let timer = null
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, args)
timer = null
}, delay);
}
}
}
可以将时间戳写法的特性与定时器写法的特性相结合,实现⼀个更加精确的节流。实现如下
function throttled(fn, delay) {
let timer = null
let starttime = Date.now()
return function () {
let curTime = Date.now() // 当前时间
let remaining = delay - (curTime - starttime) // 从上⼀次到现在,还剩下多少多余时间
let context = this
let args = arguments
clearTimeout(timer)
if (remaining <= 0) {
fn.apply(context, args)
starttime = Date.now()
} else {
timer = setTimeout(fn, remaining);
}
}
}
2.2 防抖
简单版本的实现
function debounce(func, wait) {
let timeout;
return function () {
let context = this; // 保存this指向
let args = arguments; // 拿到event对象
clearTimeout(timeout)
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
}
防抖如果需要⽴即执⾏,可加⼊第三个参数⽤于判断,实现如下:
function debounce(func, wait, immediate) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout); // timeout 不为null
if (immediate) {
let callNow = !timeout; // 第⼀次会⽴即执⾏,以后只有事件执⾏后才会再次触发
timeout = setTimeout(function () {
timeout = null;
}, wait)
if (callNow) {
func.apply(context, args)
}
}
else {
timeout = setTimeout(function () {
func.apply(context, args)
}, wait);
}
}
}
3 区别
相同点:
- 都可以通过使⽤ setTimeout 实现
- ⽬的都是,降低回调执⾏频率。节省计算资源
不同点:
- 函数防抖,在⼀段连续操作结束后,处理回调,利⽤ clearTimeout 和 setTimeout 实现。函数节流,在⼀段连续操作中,每⼀段时间只执⾏⼀次,频率较⾼的事件中使⽤来提⾼性能
- 函数防抖关注⼀定时间连续触发的事件,只在最后执⾏⼀次,⽽函数节流⼀段时间内只执⾏⼀次,例如,都设置时间频率为500ms,在2秒时间内,频繁触发函数,节流,每隔 500ms 就执⾏⼀次。防抖,则不管调动多少次⽅法,在2s后,只会执⾏⼀次
如下图所⽰:

4 应⽤场景
防抖在连续的事件,只需触发⼀次回调的场景有:
- 搜索框搜索输⼊。只需⽤⼾最后⼀次输⼊完,再发送请求
- ⼿机号、邮箱验证输⼊检测
- 窗⼝⼤⼩ resize 。只需窗⼝调整完成后,计算窗⼝⼤⼩。防⽌重复渲染。
节流在间隔⼀段时间执⾏⼀次回调的场景有:
- 滚动加载,加载更多或滚到底部监听
- 搜索框,搜索联想功能