throttle(节流函数) 与 debounce(防抖动函数)理解与实现

我们会对一些触发频率较高的事件进行监听,(如:resize scroll keyup事件)

如果在回调里执行高性能消耗的操作(如反复操作dom, 发起ajax请求等),反复触发时会使得性能消耗提高,浏览器卡顿,用户使用体验差。

或者我们需要对触发的事件延迟执行回调,此时可以借助throttle/debounce函数来实现需求。

 

throttle: 节流函数

  在一个时间段内只执行一次

debounce:防抖函数

  连续触发事件的时候,事件监听函数不会立即执行,而是等我们一段时间内不再触发事件的时候,再执行事件监听函数。

 

throttle函数实现

//通过时间来实现
function throttle (func, wait) {
  var lastTime = 0;
  return function () {
    var _this = this;
    var time = Date.now();
    if (time - lastTime >= wait) {
      func.apply(this, arguments);
      lastTime = time;
    };
  };
};

// handler 是事件监听函数
var handler = function () {
  console.log('throttle');
};

window.onscroll = throttle(handler, 300);
// setTimeout方法实现
var throttle = function(func, delay) {            
  var prev = Date.now();            
  return function() {                
    var context = this;                
    var args = arguments;                
    var now = Date.now();                
    if (now - prev >= delay) {                    
      func.apply(context, args);                    
      prev = Date.now();                
    }            
  }        
}        
function handle() {            
  console.log(Math.random());        
}        
window.addEventListener('scroll', throttle(handle, 1000));

 

 

debounce函数实现

function debounce (func, wait) {
  var timer = null;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(func, wait);
  };
};

// handler 是事件监听函数
var handler = function () {
  console.log('debounce');
};

window.onscroll = debounce(handler, 300);

 

 

  

posted @ 2019-07-25 14:53  Mr_R  阅读(531)  评论(0编辑  收藏  举报