节流(Throttling) & 防抖(Debouncing)

  •  执行函数
function doSth(sth){
    console.log(sth)
}
  • 防抖
function debounce(fn,wait){
    let timer
    return (...args)=>{
        timer && clearTimeout(timer)
        timer = setTimeout(()=>{
            fn.apply(this,args)
            timer = null
        },wait)
    }
}

时间戳版与定时器版区别:时间戳版会立即执行第一次,定时器版会按照delay时间后执行

  • 节流时间戳版  
function throttle(fn, delay) {
    let last
    return (...args) => {
        let now = +new Date()
        if (!last || now >= last + delay) {
            last = now
            fn.apply(this,args)
        }
    }
}
  • 节流定时器版
function throttle(fn,wait){
    let timer
    return (...args)=>{
        if(!timer){
            timer = setTimeout(()=>{
                fn.apply(this,args)
                timer = null
            },wait)
        }
    }
}
  • 节流css版
@keyframes pointer-events {
    from {
        pointer-events: none;
    }
    to {
        pointer-events: all;
    }
}

.throttle{
    animation: pointer-events 3s step-end forwards;
    &:active{
        animation: none;
    }
}

注:无法确定返回函数在何处调用,所以执行fn函数时对其进行绑定this指向

posted @ 2020-05-26 12:51  671_MrSix  阅读(273)  评论(0编辑  收藏  举报