看过很多关于防抖节流的文章,总是记不住原理,最近看视频,发现视频中提供的思路很容易理解

// 防抖
// 思路:fn必须由定时器调用,用户触发就重置定时器
function debounce(fn, delay){
    let timer = null
    return (...args)=>{
        // 用户调用就重置定时器
        if(timer){
            clearTimeout(timer)
        }
        // fn只能由定时器调用
        timer = setTimeout(()=>{
            fn.apply(this, args)
        },delay)
    }
}
// 节流
// 思路:如果当前时间和上次调用时间超过delay就执行fn
function throttle(fn, delay){
    // 上次调用时间
    let last = 0
    return (...args)=>{
        // 当前时间
        const now = new Date().getTime()
        // 两次调用时间超过delay就执行
        if(noe - last > delay){
            last = now 
            fn.apply(this, args)
        }
    }
}

上述对于理解怎么简单实现防抖节流比较方便,较为详细的实现方式可以参考冴羽大佬的防抖以及节流