防抖节流
防抖:
多次连续触发,按最后一次触发事件超过500毫秒执行
let debounce = (fn, wait=500) => { let timer return function(...args) { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { fn.apply(this, args) },wait) } }
节流:
按固定时间执行
let throttle = (fn, wait=1500) => { let lastTime = 0 return function (...args) { const now = new Date() if (now - lastTime > wait) { fn.apply(this,args) lastTime = now } } }
使用:
window.addEventListener('scroll', throttle(() => { console.log('滚动监听') }))