1. 是什么
本质是优化高频率执行代码的手段,比如 scroll keypress mousemove等事件。
定义
防抖(debounce):在事件被触发n秒后在执行回调,如果在这n秒内又被触发,测重新计时。
节流(throttle):在规定的时间间隔内,只触发一次回调函数,如果规定时间内触发多次函数,只有一次生效。
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 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);
}
}
}