简单实现函数节流与防抖

63 阅读1分钟

定义

  • 节流:在n秒内调用某函数m次 则实际仅执行函数一次
  • 防抖:函数调用后等待n秒执行,若等待过程中函数被调用则重新开始记时

代码实现

节流

利用记时器保证执行最后一次调用

function myThrottled(fn,delay=500){ 
    let timer = null;
    return function(...arg){
        let context =this;
        if(timer){ //有函数等待执行 本次调用不生效
            return
        }
        timer=setTimeout(function(){
            fn.apply(context,arg)
            timer=null //执行完毕,新的调用可执行
        },delay)
    }
}

防抖

function myDebounce (fn,delay=500){ //防抖
    let startTime = 0
    return function(...arg){
        startTime=Date.now(); //重复调用重新记时
        setTimeout(function(){
            let now=Date.now()
            if(now-startTime>=delay){
                fn(...arg)
            }
        },delay)
    }
}

应用场景

获取页面滚动距离

function scrollTop(msg) {
    console.log(Date.now())
    console.log(`${msg}${document.documentElement.scrollTop}`)
}
let scrollTopThrottled=myThrottled(scrollTop,1000)
let scrollTopDebounce = myDebounce(scrollTop,5000)
window.onscroll = function () {
    // scrollTop('持续获取距离')
    scrollTopDebounce('滚动停止5s后 输出滚动距离')
    // scrollTopThrottled('间隔1s 输出滚动距离')
}