Loading

「跟着渡一学前端」手写节流函数

学习资源

完整代码

function throttle(fn, wait) {
  let lastTime = null;
  return function (...args) {
    const now = Date.now();
    if (lastTime === null || now - lastTime > wait) {
      lastTime = now;
      return fn.apply(this, args);
    }
  }
}

const log = throttle(console.log, 1000);

知识细节

  • 节流和防抖可以理解为王者中的
    • 回城——防抖
    • 技能CD——节流
  • lastTime记录上一次执行时间
  • 代码逻辑
    1. 只有上次没有触发过,或者上一次执行时间已经超过等待时间才会再次触发。
    2. 更新上次执行时间(lastTime)值。
    3. 执行函数。
  • 第3行不能用箭头函数替换,否则第7行中的this指向会出问题
posted @ 2025-02-16 22:12  lao-jiawei  阅读(16)  评论(0)    收藏  举报