#防抖与节流

#防抖

防抖就是越调用越推迟执行

/**
 * 防抖
 */
export function debounce<T>(fn: (...args: T[]) => void, ms = 1000) {
  let timer: ReturnType<typeof setTimeout> | null = null

  return function (this: ThisParameterType<typeof fn>, ...args: T[]) {
    if (timer) {
      clearTimeout(timer)
    }

    timer = setTimeout(() => fn.apply(this, args), ms)
  }
}

#节流

节流就是管你怎么调用,我就 ms 秒调用一次

/**
 * 节流
 */
export function throttle<T>(fn: (...args: T[]) => void, ms = 1000) {
  let timer: ReturnType<typeof setTimeout> | null = null

  return function (this: ThisParameterType<typeof fn>, ...args: T[]) {
    if (timer) return

    timer = setTimeout(() => {
      fn.apply(this, args)
      timer = null
    }, ms)
  }
}

#css 节流

通过以下三个属性 pointer-events:禁止按钮事件 animation:控制节流时间 :active:触发节流

button {
  animation: throttle 2s step-end forwards;
}
button:active {
  animation: none;
}
@keyframes throttle {
  from {
    pointer-events: none;
  }
  to {
    pointer-events: all;
  }
}

注意,这里动画的缓动函数设置成了阶梯曲线,step-end,它可以很方便的控制 pointer-events 的变化时间点。简单来说就是突变。

但是按钮一开始是在禁用的 而且 css 限制并不安全