防抖动、节流阀函数、柯里化函数

防抖(Debounce)和节流(throttle)都是用来控制某个函数在一定时间内执行多少次的技巧,两者相似而又不同。

防抖函数

防抖是指在一定时间内只执行一次事件,接下来我们看一下实例。

function debouce(hanlder, wait) {
    var t = null;
    return function () {
        clearTimeout(t);
        t = setTimeout(hanlder, wait);
    }
}

function hanlder() {
    console.log('scroll~~~~');
}

window.addEventListener('scroll', debouce(hanlder, 500));
debouce.gif

节流函数

节流函数,只允许一个函数在规定的时间内执行一次。同样,我们现在来看一下实现方案:

var throttle = function (func, wait){
  var timeout,
      context,
      args,
      startTime = Date.parse(new Date());
  
  return function(){
    var curTime = Date.parse(new Date());
    var remaining = wait - (curTime - startTime);
    context = this;
    args = arguments;
    
    clearTimeout(timeout);
    
    if(remaining <= 0){
      func.apply(context, args);
      startTime = Date.parse(new Date());
    }else{
      timeout = setTimeout(func, remaining);
    }
  }
};

柯里化函数

function curry(fn) {
  let args = [];
  return function result(...rest) {
    if (rest.length === 0) {
        return fn(args);
    }

    args.push(...rest);
    return result;
  }
}

你可能感兴趣的:(防抖动、节流阀函数、柯里化函数)