# 节流防抖

# 节流防抖的区别

  • 防抖函数:疯狂点击按钮,每次点击的时间间隔都小于规定时间,那么相应的方法不会执行(即定时器如果没有到timer的时间,再次执行函数,会重新计时。)
  • 节流函数:疯狂点击按钮,规定的时间间隔内只触发一次相应的方法

# throttle 节流

比如drag拖拽事件,window.onresize()等。 正常情况下 drag事件,onresize() 每秒都会触发很多次。但是实际上我们并不需要频繁的触发。此时可以使用节流固定频率触发函数。不然频繁触发会导致卡顿。

    //setTimeOut实现
    function throttle(fn,delay = 1000){
        let timer = null;
        if(timer) return;
        return function (){
            setTimeOut(()=>{
                return fn.apply(this,arguments)
            },delay)
        }
    }
    //时间戳实现
    function throttle(fn,delay = 1000){
        let timer = 0;
        return function (){
            const nowDate = Date.now();
            if(nowDate - timer > delay){
                timer = nowDate;
                return fn.apply(this,arguments)
            }
        }
    }

# debounce 防抖

  • 使用场景 监听一个输入框 文字变化就会触发 change事件
  • 监听keyup 键盘只要打字就会触发change事件。 防抖:用户输入完,才触发请求。 比如间断500ms才执行一次事件。
function debounce(fn,delay = 500){
    let timer = null;//闭包,使用 return的fn在闭包中定义。
    return function (){
        if(timer){
            clearTimeout(timer)
        }
        timer =  setTimeout(function(){
            fn.apply(this,arguments)
            timer = null;
        },delay)
    }
}

const input1 = document.getElementById('txt') 
input1.addEventListener('keyup',debounce(function(){
    console.log('111')
},1000))