防抖节流

防抖

// 使用定时器实现
function debounce(fn, delay) {
  let timer = null;
  return (...args) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}
// 测试用,需要改变窗口大小
window.onresize = debounce(function() {
  console.log(111, arguments);
}, 500);

节流

// 1.时间戳方式
function throttle(fn, delay) {
  let pre = 0;
  return (...args) => {
    let now = new Date().getTime();
    if (now - pre > delay) {
      fn.apply(this, args);
      pre = now;
    }
  };
}
// 2.定时器方式
function throttle(fn, delay) {
  let timer = null;
  return (...args) => {
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args);
        timer = null;
      },delay);
    }
  };
}
// 测试用,需要改变窗口大小
window.onresize = throttle(function () {
  console.log(111, arguments);
}, 2000);

你可能感兴趣的:(防抖节流)