节流(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)
    }
}
  • 节流时间戳版  
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)
        }
    }
}

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