yang-xianzhu / astro-blog

🚀-基于Astro搭建的个人博客
https://yang-xianzhu.github.io/
5 stars 0 forks source link

面试官: 说一下函数节流和函数防抖 #9

Open yang-xianzhu opened 1 year ago

yang-xianzhu commented 1 year ago
// 定时器版
function throttle(fn: Function, wait: number = 500) {
  let timeId: null | number = null;

  return function (...args: Array<any>) {
    if (timeId) {
      return;
    }

    timeId = setTimeout(() => {
      fn.apply(this, args);
      timeId = null;
    }, wait);
  };
}

// 时间戳版
function throttle(fn: Function, wait: number = 500) {
  //  记录上一次时间戳
  let prevTime = Date.now();

  return function (...args: Array<any>) {
    // 获取当前时间戳
    let currentTime = Date.now();
    if (currentTime - prevTime >= wait) {
      fn.apply(this, args);
      prevTime = currentTime;
    }
  };
}
// 定时器版
function debounce(fn: Function, wait: number = 500) {
  let timeId: null | number = null;

  return function (...args: Array<any>) {
    if (timeId) {
      clearTimeout(timeId);
    }

    timeId = setTimeout(() => {
      fn.apply(this, args);
    }, wait);
  };
}

// 可立即执行版
function debounce(fn: Function, wait: number = 500, immediate: boolean = true) {
  let timeId: null | number = null;
  return function (...args: Array<any>) {
    if (timeId) clearTimeout(timeId);

    // 如果是立即执行
    if (immediate) {
      let callNow = !timeId;
      timeId = setTimeout(() => {
        timeId = null;
      }, wait);
      if (callNow) {
        fn.apply(this, args);
      }
      return;
    }

    timeId = setTimeout(() => {
      fn.apply(this, args);
    }, wait);
  };
}