Skip to content

函数的节流和防抖

发表于
更新于
阅读量

节流

概念:事件触发后每个一段事件触发一次,可以触发多次

应用:scroll,resize事件一段事件触发多次

javascript
let throttle = function(func,delay){
    let timer = null
    return function(){
        if(!timer){
            timer = setTimeout(() => {
                func.apply(this,arguments);
                // 或者直接func()
                timer = null
            },delay)
        }
    }
}

防抖

概念:事件触发动作完成后一段事件触发一次

应用:scroll,resize事件触发完后一段时间触发

javascript
let debounce = function(fn,wait){
    let timer = null
    return function(){
        if(timer){
            clearTimeout(timer)
        }
        timer = setTimeout(()=>{
            fn.apply(this,arguments)
            // 或者直接fn()
            timeout = null
        },wait)
    }
}

//处理函数
function handle(){
    console.log(arguments)
    console.log(Math.random)
}

//测试用例
document.getElementsByClassName('scroll-box')[0].addEvenetListener('scroll',debounce(handle,3000))

Released under the MIT License.