函数节流throttling和函数防抖debounceJavaScript实现

函数节流

function throttle(fn, delay = 1000, immediate = true) {
  let Running = false;
  return () => {
    if (!Running) {
      Running = true;
      immediate === false && fn.apply(this, arguments);
      setTimeout(() => {
        immediate && fn.apply(this, arguments);
        Running = false;
      }, delay);
    }
  };
}

用法

function OnClick() {
  console.log('Clicked!');
}
let clicked = throttle(OnClick, 1000);

clicked();
//'Clicked!'
clicked();
clicked();

函数防抖

function debounce(fn, delay = 1000) {
  let timer = false;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(this, arguments);
    }, delay);
  }
}

用法

function OnClick(){
    console.log('Clicked!');
}
let clicked = debounce(OnClick,1000);

clicked();
clicked();
clicked();
//'Clicked!'
posted @ 2019-04-16 12:57  limbobark  阅读(340)  评论(0编辑  收藏  举报