【Vue】JS中防抖与节流

【Vue】JS中防抖与节流

概要

//节流 必须等待规定的秒数之后才能执行下一次该函数
function throttle(fn, interval) {
  let last = 0;
  return function () {
    let context = this;
    let args = arguments;

    let now = +new Date();
    if (now - last > interval) {
      last = now;
      fn.apply(context, args);
    }
  };
}

//防抖 该函数每次被调用都会重新计算时间,在最后一次调用之后会延迟delay时间后
function debounce(fn, delay) {
  let timer = null;
  return function (params) {
    let context = this;
    let args = arguments;
    if (timer) clearTimeout(timer);

    timer = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  };
}

//防抖 跟上个方法一样,但是时间不重新计算
function betterDebounce(fn, delay) {
  let last = 0;
  let timer = null;
  return function (params) {
    let context = this;
    let args = arguments;
    let now = +new Date();
    if (now - last < delay) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(context, args);
        last = now;
      }, delay);
    } else {
      last = now;
      fn.apply();
    }
  };
}

|ू・ω・` )最后附上 -> 个人博客地址

你可能感兴趣的:(vue,html)