函数防抖与函数节流

289 阅读1分钟
用户行为会频繁的触发事件执行,对于DOM操作、资源加载等耗费性能的处理,很可能导致界面卡顿,甚至浏览器的崩溃。函数节流(throttle)和函数防抖(debounce)就是为了解决类似需求应运而生的。


函数防抖


规定函数至少间隔多久执行。

  • 函数执行过一次后,在n秒内不能再次执行,否则推迟函数执行
  • 下一次函数调用将清除上一次的定时器,并用setTimeout重新计时


function debounce(method, delay){
    var timer = null;
    return function(){
        var context = this,args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function(){
            method.apply(context, args);
        },delay);
    }
}

document.getElementById('debounce').onclick = debounce(function(){console.log('click')},2000);


函数节流

规定函数在某时间段内最多执行一次

  • 函数在n秒内最多执行一次
  • 下一次函数调用将清除上一次的定时器
    • 若函数执行的时间间隔小于等于规定时间间隔则用setTimeout在规定时间后再执行
    • 若函数执行的时间间隔大于规定时间间隔则执行函数,并重新计时


function throttle(method, delay){
    var last = 0;
    return function (){
        var now = +new Date();
        if(now - last > delay){
            method.apply(this,arguments);
            last = now;
        }
    }
}

document.getElementById('throttle').onclick = throttle(function(){console.log('click')},2000);

区别

函数节流:是确保函数特定的时间内至多执行一次。
函数防抖:是函数在特定的时间内不被再调用后执行。


https://blog.csdn.net/qq_37860930/article/details/83505547

https://juejin.cn/post/6844903651278848014