性能优化
防抖
防抖(debounce)
所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间
const box = document.querySelector('.box')
let count = 0
function mouseMove () {
box.innerHTML = ++count
}
function debounce (fn, t = 500) {
let timer
return function () {
if(timer) clearTimeout(timer)
timer = setTimeout(fn, t)
}
}
//自定义
// box.addEventListener('mousemove', debounce(mouseMove, 500))
//Lodash库
box.addEventListener('mousemove', _.debounce(mouseMove, 500))
节流
节流(throttle)
所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数
使用场景 :轮播图点击效果 、 鼠标移动、页面尺寸缩放resize、滚动条滚动 就可以加节流