JS函数节流防抖

用户行为会频繁的触发事件执行,而对于DOM操作、资源加载等耗费性能的处理,很可能导致界面卡顿,甚至浏览器的崩溃。

1、函数节流(throttle)

  预先设定一个执行周期,当调用动作的时刻大于等于执行周期则执行该动作,然后进入下一个新周期。

场景:

  • 窗口调整(resize)
  • 页面滚动(scroll)
  • 抢购疯狂点击(mousedown)
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')},3000);

2、函数防抖(debounce)

  当调用动作n毫秒后,才会执行该动作,若在这n毫秒内又调用此动作则将重新计算执行时间

场景:

  • 实时搜索(keyup)
  • 拖拽(mousemove)
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')},3000);

程序员兼职

原文地址:https://www.cnblogs.com/vhen/p/7685366.html