防抖节流

防抖:

多次连续触发,按最后一次触发事件超过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('滚动监听')

}))

 


posted @ 2020-01-05 12:16  庄翠的博客  阅读(197)  评论(0编辑  收藏  举报