学习笔记 - 节流和防抖

108 阅读1分钟

一、节流throttle

当前操作每隔internal时间,只触发第一次请求

原理

使用闭包,将上次触发事件的时间存放在内存中

手写节流

function throttle(fn, interval) {
    let last = 0
    
    return function(...args) {
        let now = +new Date() // 转换为时间戳
        if (now - last > interval) {
            fn.call(this, ...args)
            last = now
        }
    }
}

二、防抖debounde

当前操作隔internal时间后再发送一次请求 ,也即等操作稳定下来且internal时间内没有新的触发

原理

闭包存放定时器timeId

手写防抖

思路:

1.隔delay时间之后再触发,因此用定时器 2.闭包中存放的是定时器id

 function debounce(fn, delay) {
    let timer = null 
    return function(...args){
        const context = this
        if (timer) { 
            // 再次触发时,如果定时器时间没到,就取消定时器的执行
            clearTimeout(timer)
        }
        timer = setTimeout(function() {
            console.log('-------d-----')
            fn.call(context, ...args)
        }, delay)
    }
}

三、相同点

使用场景

一些window短时间内可能会被反复触发的事件,比如scroll、resize、mosemove、moseover、keyup、keydown等等

图片懒加载过程中,队懒加载函数做节流处理,对应的事件是scroll

相同原理

都是使用闭包

四、总结

还是要多写啊,老是忘记。。。