javascript - 关于 throttle 函数的问题
ringa_lee
ringa_lee 2017-04-11 12:29:04
[JavaScript讨论组]
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));

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

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

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
ringa_lee

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));
PHP中文网

可以参考下我关于节流、去抖的文章 https://github.com/hanzichi/u...

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号