函数节流和函数防抖

116 阅读1分钟

函数节流

规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。

一个形象的例子就是游戏中技能的CD时间。

function throttle(fn,delay){
    let canUse=true
    return function(){
        if(canUse){
            fn.apply(this,arguments)
            canUse=false
            setTimeout(()=>canUse=true,delay)
        }
    }
}

const throttled  = throttle(()=>console.log('hi'))
throttled()
throttled()
throttled()
 // 只会输出一个hi,因为在CD

函数防抖

在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。

有点像坐电梯,假设每个人都会按电梯按钮,那么每次有人进来时电梯的关门时间就会重置。

function debounce(fn,delay){
    let timerId = null
    return function(){
        const context = this
        if(timerId){window.clearTimeout(timerId)}
        timerId=>setTimeout(()=>{
        fn.apply(context,arguments)
        timerId=null
        },delay)
    }
}

const debounced = debounce(()=>console.log('hi'))
debounced()
debounced()