javascript - 关于 throttle 函数的问题

查看:61
本文介绍了javascript - 关于 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));

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

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

解决方案

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

这篇关于javascript - 关于 throttle 函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆