看过很多关于防抖节流的文章,总是记不住原理,最近看视频,发现视频中提供的思路很容易理解
// 防抖
// 思路: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)
        }
    }
}
- 本文链接:https://harry-qi.github.io/2021/11/07/%E9%98%B2%E6%8A%96%E8%8A%82%E6%B5%81/
 - 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。