文章内容输出来源:拉勾教育前端高薪训练营
为什么需要防抖和节流
在网页应用或app操作时,经常会有轮播图切换、点击操作、鼠标滚动(scroll)、调整窗口大小(resize)、敲击键盘输入匹配(keyup)等这些高频率事件,这类事件在触发时往往频率极高,如果不加以限制,往往会频繁的执行代码逻辑或频繁的修改DOM,此时就有可能造成程序的卡顿等问题。
浏览器默认情况下都会有自己的监听事件间隔(4ms-6ms),但是这对于运行环境来说间隔时间往往太短,为了规避次类型的问题,我们往往会使用节流(throttle)或者防抖(debounce)来进行处理。
什么是节流和防抖
- 防抖:抖动就是短时间内高频触发,对于这个高频的操作来说,我们只希望识别一次点击,可以是人为的第一次或者是最后一次
- 节流:对于高频操作,我们可以自己来设置频率,让本来会执行很多次的事件触发,按着我们定义的频率减少触发的次数
模拟防抖函数
/**
* 防抖函数
*
* @param {*} handle 执行的事件
* @param {*} wait 执行间隔事件
* @param {*} immediate 是否立即执行
*/
function debounce(handle, wait, immediate) {
if (typeof handle !== 'function') throw new Error('handle must be an function')
if (typeof wait === 'undefined') wait =300
if (typeof wait === 'boolean') {
immediate = wait
wait = 300
}
if (typeof immediate !== 'boolean') immediate = false
let timer = null
return function proxy(...args) {
const self = this
const init = immediate && !timer
clearTimeout(timer)
timer = setTimeout(() => {
timer = null
!immediate ? handle.call(self, ...args) : null
}, wait);
// 当传进来immediate为true,立即执行
init ? handle.call(self, ...args) : null
}
}
模拟节流函数
/**
* 节流函数
*
* @param {*} handle 执行的事件
* @param {*} wait 执行间隔事件
*/
function throttle(handle, wait) {
if (typeof handle !== 'function') throw new Error('handle must be an function')
if (typeof wait === 'undefined') wait =500
let pre = 0
let timer = null
return function proxy(...args) {
const now = new Date()
const self = this
const interval = wait - (now - pre)
if (interval <= 0) {
clearTimeout(timer)
timer = null
handle.call(self, ...args)
pre = new Date()
} else if (!timer) {
timer = setTimeout(() => {
clearTimeout(timer)
timer = null
handle.call(self, ...args)
pre = new Date()
}, interval);
}
}
}