一、防抖(debounce)
- 触发事件后在设置时间内函数只执行一次,如果期间又触发了事件,则会重新计算函数执行时间
// 防抖函数
export const debounce = (fn, delay) => {
let timer = null
const that = this
return function() {
if (timer) { clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(that, arguments)
}, delay)
}
}
场景
- search搜索联想,用户不断输入值,用防抖来节约请求
- window触发resize的时候,不断地调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次
二、节流(throttle)
- 对于短时间内大量触发同一事件,在设置的时间范围内只执行一次行
// 节流函数
export const throttle = (fn, delay) => {
let timer = null
const that = this
return function() {
if (!timer) {
timer = setTimeout(() => {
timer = null
fn.apply(that, arguments)
}, delay)
}
}
}
场景
总结
- 在一定时间内多次触发,不想要执行你的方法,就需要清除之前触发的定时器,因此我们就采用timer来存储
- timer来存储,意味着这个变量就一直在内存当中,所以这里采用 闭包 的方式