lodash中的throttle与debounce使用详解
在前端开发中,节流(throttle)和防抖(debounce)是常用的性能优化手段。lodash库提供了成熟的实现方案,本文详细介绍它们的API、使用场景以及在Vue和React中的集成方式。
1. 节流 (throttle)
_.throttle(func, [wait=0], [options={}])
参数说明:
func(Function): 需要限制执行频率的函数[wait=0](number): 执行间隔的毫秒数[options={}](Object): 配置选项[options.leading=true](boolean): 是否在节流开始时立即调用,默认true[options.trailing=true](boolean): 是否在节流结束后再调用一次,默认true
实例说明:
const handleThrottle = _.throttle(function() {
console.log("throttle executed");
}, 5000, {
leading: true,
trailing: false
});
当按钮绑定handleThrottle时,效果如下:
- 首次点击立即输出 "throttle executed"
- 5秒内重复点击只触发一次
- 5秒后再次点击会重新触发
注意:当trailing为true(默认值)时,节流结束时会额外执行一次,表现为点击后立即执行一次,5秒后再执行一次。
2. 防抖 (debounce)
_.debounce(func, [wait=0], [options={}])
参数说明:
func(Function): 需要防抖的函数[wait=0](number): 延迟执行的毫秒数[options={}](Object): 配置选项[options.leading=false](boolean): 是否在延迟开始前立即调用,默认false[options.maxWait](number): 允许函数被延迟的最大时间[options.trailing=true](boolean): 是否在延迟结束后调用,默认true
实例说明:
const handleDebounce = _.debounce(function() {
console.log("debounce executed");
}, 2000, {
leading: true,
trailing: false
});
绑定按钮后的表现:
- 首次点击立即输出 "debounce executed"
- 连续点击多次只触发一次(以最后一次点击为准)
- 停止点击后等待2秒不再触发
默认配置下(leading为false,trailing为true),函数会在停止触发后2秒执行。
3. Vue中的集成方式
安装lodash:
# Yarn
$ yarn add lodash
# NPM
$ npm install lodash --save
节流用法:
<template>
<button @click="throttledMethod">快速点击我</button>
</template>
<script>
import _ from 'lodash'
export default {
methods: {
throttledMethod: _.throttle(() => {
console.log('每2秒最多执行一次')
}, 2000)
}
}
</script>
防抖用法:
<template>
<button @click="debouncedMethod">快速点击我</button>
</template>
<script>
import _ from 'lodash'
export default {
methods: {
debouncedMethod: _.debounce(() => {
console.log('停止点击2秒后执行')
}, 2000)
}
}
</script>
4. React中的集成方式
import _ from 'lodash';
class MyComponent extends React.Component {
// 防抖
handleClick = _.debounce((e) => {
console.log('防抖触发,5秒内不重复点击才执行');
}, 5000, {
leading: true,
trailing: false
});
// 节流
handleScroll = _.throttle((e) => {
console.log('节流触发,5秒内最多执行一次');
}, 5000, {
leading: true,
trailing: false
});
render() {
return (
<button onClick={this.handleClick}>点击按钮</button>
);
}
}
在React中,可以直接在类组件中将lodash的debounce或throttle方法赋值给类方法,但需要注意箭头函数的绑定方式。