防抖截流函数

160 阅读1分钟

防抖函数

顾名思义就是防止抖动,比如输入框输入的时候,绑定的数据会一直改变,如果此时想要在输入结束才去进行接口请求等操作,就需要用到防抖函数,他的作用就是当持续触发的时候,函数是不执行的,等最后一次触发结束的一段时间之后再去执行,比如输入结束之后再去进行接口搜索回显数据。

// 防抖函数
//使用箭头函数
function debounce(fn, delay = 500) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.call(this, args);
    }, delay);
  };
}
​
// 不使用箭头函数
function debounce2(fn, delay = 500) {
  let timer;
  return function() {
      let _this = this;
      let _args = arguments;
      if(timer) { clearTimeout(timer) }
      timer = setTimeout(function(){
          fn.apply(_this, args)
      }, wait);      
  }
}

节流函数

函数节流的目的,是为了限制函数一段时间内只能执行一次。 因此,通过使用定时任务,延时方法执行。 在延时的时间内,方法若被触发,则直接退出方法。 从而实现一段时间内只执行一次。

//节流的目的是让函数执行的频率变低
//时间戳版本
function throttle(fn, delay = 500) {
  let initTime = 0;
  return function() {
    let now = +new Date();
    let _this = this;
    let _arg = arguments;
    if(now - initTime > delay) {
      fn.apply(_this, _arg);
      initTime = now;
    }
  }
}
​
//定时器版本
function throttle2(fn, delay = 500){
  let timer = null;
  return function() {
    let _this = this;
    let _args = arguments;
    if(!timer) {
      timeout = setTimeout(function(){
        timer = null;
        fn.apply(_this, _args);
      }, delay)
    }
  }
}