JS - Lodash工具库的使用详解2(使用throttle函数实现节流)

作者: hgweb 发布时间: 2019-10-11 浏览: 2912 次 编辑

二、使用 throttle 函数实现节流

1,throttle 节流

throttle 函数原型如下。它会创建一个节流函数,在 wait 秒内最多执行 func 一次的函数。

_.throttle(func, [wait=0], [options={}])

(1)throttle 的功能和前文介绍的 debounce 很像,都是为了防止某个方法被频繁调用。不同的是,throttle 可以指定每隔多长时间允许执行一次。
(2)options 有如下两个可选参数配置:

  • leading:指定在节流开始前是否执行 func(默认为 true)。
  • trailing:指定在节流结束后是否执行 func(默认为 true)。

2,使用样例

(1)效果图

  • 点击按钮界面会在控制台中打印消息(包括打印时的时间)。
  • 但如果我们连续点击按钮,消息并不会连续打印,而是 1 秒钟内最多打印一条消息。

原文:JS - Lodash工具库的使用详解2(使用throttle函数实现节流)

(2)样例代码

<template>
  <div id="test">
    <button @click="btnClick">点击</button>
  </div>
</template>
  
<script>
  
import _ from 'lodash';
  
export default {
  name: 'Test',
  data () {
    return {
    }
  },
  methods:{
    //按钮点击
    btnClick() {
      //打印消息
      this.showAlert('欢迎访问hangge.com');
    },
    // 显示消息时增加节流(最多1秒钟执行一次)
    showAlert: _.throttle(function(message){
      console.log((new Date()).format("hh:mm:ss"), message);
    }, 1000)
  },
  // 页面创建时自动加载数据
  created() {
  }
}
</script>

(3)上面代码也可改成如下形式,效果是一样的:

<template>
  <div id="test">
    <button @click="showAlert('欢迎访问hangge.com')">点击</button>
  </div>
</template>
  
<script>
  
import _ from 'lodash';
  
export default {
  name: 'Test',
  data () {
    return {
    }
  },
  methods:{
    // 显示消息时增加节流(最多1秒钟执行一次)
    showAlert: _.throttle(function(message){
      console.log((new Date()).format("hh:mm:ss"), message);
    }, 1000)
  },
  // 页面创建时自动加载数据
  created() {
  }
}
</script>

附:throttle 其它的一些应用场景

Lodash 的官方在线手册(点击跳转)中还列举了一些 throttle 函数的使用场景,具体如下:

// 避免在滚动时过分的更新定位
jQuery(window).on('scroll', _.throttle(updatePosition, 100));
  
// 点击后就调用 `renewToken`,但5分钟内超过1次。
var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
jQuery(element).on('click', throttled);
  
// 取消一个 trailing 的节流调用。
jQuery(window).on('popstate', throttled.cancel); 

JS Lodash工具库的使用详解系列:

JS - Lodash工具库的使用详解1(使用debounce函数实现防抖)

JS - Lodash工具库的使用详解2(使用throttle函数实现节流)

JS - Lodash工具库的使用详解3(String字符串操作函数)

JS - Lodash工具库的使用详解4(Array数组函数1:查找指定元素、或索引)

JS - Lodash工具库的使用详解5(Array数组函数2:获取部分数组片段)

JS - Lodash工具库的使用详解6(Array数组函数3:移除、修改原数组内容)

JS - Lodash工具库的使用详解7(Array数组函数4:数组排序、打乱)

JS - Lodash工具库的使用详解8(Array数组函数5:数组与对象间的转换)

JS - Lodash工具库的使用详解9(Array数组函数6:如果不是数组强制转成数组)

JS - Lodash工具库的使用详解10(Array数组函数7:根据指定规则进行分组、统计)

JS - Lodash工具库的使用详解11(Array数组函数8:创建指定范围数字的数组)

JS - Lodash工具库的使用详解12(创建一个只能调用1次、n次的函数)

JS - Lodash工具库的使用详解13(创建一个对某函数结果取反的函数)

JS - Lodash工具库的使用详解14(浅拷贝,深拷贝)

JS - Lodash工具库的使用详解15(深比较,判断是否包含某属性或属性值)

JS - Lodash工具库的使用详解16(判断是否为空)

JS - Lodash工具库的使用详解17(类型检查)

JS - Lodash工具库的使用详解18(生成随机数)


原文出自:www.hangge.com 转载请保留原文链接:https://www.hangge.com/blog/cache/detail_2575.html