初面网初面网

防抖和节流

防抖

function debounce(fun, delay){
  let timer
  return function(){
    if(timer) clearTimeout
    let args = arguments
    timer = setTimeout(()=>{
      fun.apply(this, args)
    }, delay)
  }
}

节流

function throttle(fun, delay){
  let start = 0
  return function(){
    let now = new Date()
    if(now - start > time){
      fun.apply(this, arguments)
      start = now
    }
  }
}

ts版本

防抖:

function debounce(func: Function, delay: number) {
  let timer: ReturnType<typeof setTimeout>;
  return function(this: any, ...args: any[]) {
    const context = this;
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(context, args);
    }, delay);
  };
}

节流:

function throttle(func: Function, delay: number) {
  let timer: ReturnType<typeof setTimeout> | null = null;
  let lastTime = 0;
  return function(this: any, ...args: any[]) {
    const context = this;
    const now = Date.now();
    if (now - lastTime >= delay) {
      func.apply(context, args);
      lastTime = now;
    } else {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        func.apply(context, args);
        lastTime = Date.now();
      }, delay - (now - lastTime));
    }
  };
}

更新于 2025/2/26