函数节流和防抖简单实现

//等delay时间执行一次
function debounce(fn, delay){
  let timer = null;
  return function(){
    let context = this;
    let args = arguments;
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  }
}
//每隔delay执行一次
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();
      }
  }
}

你可能感兴趣的:(前端开发)