手撕函数防抖和函数节流

91 阅读1分钟

一.概念

1.函数防抖

2.函数节流

二.手写函数防抖

// 防抖(一段时间会等,然后带着一起做了)

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()

三.手写函数节流

//节流(一段时间执行一次后,就不执行第二次)

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()