【Vue】JS中振れ止めと絞り

7728 ワード

【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();
    }
  };
}

|ू・ω・` )最後に添付->個人ブログアドレス