关于 throttle 函数的问题

function throttle(fn, wait) {
    let timer;

    return function (...args) {
      if(!timer) {
        timer = setTimeout(() => {
          timer = null;
        }, wait);

        return fn.apply(this, args);
      }
    }
  }

  document.querySelector('button').addEventListener('click', throttle(function () {
    console.log('我被点击啦!');
  }, 3000));

今天在学习的时候,学到了这个函数。。

可以可以详细给我讲讲这个函数的实现原理和过程,我有点似懂非懂,谢谢!

阅读 2.4k
2 个回答

Lodash throttle: Creates a throttled function that only invokes func at most once per every wait milliseconds.
throttle 函数的作用是创建一个函数,该函数在 wait 时间内只会被调用一次。

function throttle(fn, wait) {
    // 定时器
    let timer;
    
    // 返回一个函数
    return function (...args) {
      // 第一次执行时,timer是不存在的,将执行if内的代码
      if(!timer) {
        // timer被赋值,并在wait时间后重置timer为null,所以在wait时间内if内的代码都不再执行
        timer = setTimeout(() => {
          timer = null;
        }, wait);
        
        // 调用函数,并返回其值
        return fn.apply(this, args);
      }
    }
  }

  document.querySelector('button').addEventListener('click', throttle(function () {
    console.log('我被点击啦!');
  }, 3000));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题