Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

关于 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));

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...