JS - Lodash工具库的使用详解2(使用throttle函数实现节流)
作者:hangge | 2019-09-28 08:10
二、使用 throttle 函数实现节流
1,throttle 节流
throttle 函数原型如下。它会创建一个节流函数,在 wait 秒内最多执行 func 一次的函数。
_.throttle(func, [wait=0], [options={}])
(1)throttle 的功能和前文介绍的 debounce 很像,都是为了防止某个方法被频繁调用。不同的是,throttle 可以指定每隔多长时间允许执行一次。
(2)options 有如下两个可选参数配置:
(2)options 有如下两个可选参数配置:
- leading:指定在节流开始前是否执行 func(默认为 true)。
- trailing:指定在节流结束后是否执行 func(默认为 true)。
2,使用样例
(1)效果图

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

(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);
全部评论(0)