函数节流和函数防抖JavaScript实现

函数节流

function throttle(fn, delay = 1000, immediate = true) {
  let Running = false;
  return function () {
    if (Running) {
      return;
    }
    Running = true;
    if(immediate === false){
      fn();
    }
    setTimeout(function () {
      if(immediate){
        fn();
      }
      Running = false;
    }, delay);
  }
}
function OnClick() {
  console.log('Clicked!');
}
let clicked = throttle(OnClick, 1000);
用法
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();
    }, delay);
  }
}
用法
function OnClick(){
    console.log('Clicked!');
}
let clicked = debounce(OnClick,1000);

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

转载于:https://www.cnblogs.com/limbobark/p/10716326.html

你可能感兴趣的:(javascript,ViewUI)