lodash中节流(throttle)和防抖(debounce)
1.节流
throttle API
_.throttle(func, [wait=0], [options={}])
func (Function): 要节流的函数。
[wait=0] (number): 需要节流的毫秒数。
[options={}] (Object): 选项对象。
[options.leading=true] (boolean): 指定调用在节流开始前,默认true。
[options.trailing=true] (boolean): 指定调用在节流结束后,默认true。
用法
testThrottle: _.throttle(function() {
console.log("throttle");
}, 5000, {
leading: true,
trailing: false
})
说明:
testThrottle方法被绑定在一个按钮上,demo最终的效果是 :
1、按钮点击后控制台立马打印了throttle——19:39:00;
2、5秒内点击多次按钮,最终只打印一次throttle——19:39:05前;
3、5秒后再点击一次,会重新打印throttle——19:39:05后;
PS:lodash默认trailing为true,那么最终的效果是在点击时会立即打印throttle,且5秒后又会再打印一次,即节流之前和之后都会执行该节流函数。
2.防抖
debounce API
_.debounce(func, [wait=0], [options={}])
func (Function): 要防抖动的函数。
[wait=0] (number): 需要延迟的毫秒数。
[options={}] (Object): 选项对象。
[options.leading=false] (boolean): 指定在延迟开始前调用,默认false。
[options.maxWait] (number): 设置 func 允许被延迟的最大值。
[options.trailing=true] (boolean): 指定在延迟
用法:
testDebounce: _.debounce(function() {
console.log("debounce");
}, 2000, {
leading: true,
trailing: false
})
说明:
1、按钮点击后控制台立马打印了debounce——19:39:00;
2、5秒内点击多次按钮,最终只打印一次debounce——19:39:05前,假设19:39:04完成了最后一次点击;
3、相对于最后一次点击的5秒后再点击一次,会重新打印debounce——19:39:09后;
PS:lodash默认leading为false、trailing为true,那么最终的效果是在点击后等待5秒才会打印debounce,即延迟之前不执行函数,而是在延迟之后执行
3.vue内对这两种防抖截流的使用方法
安装:
# Yarn
$ yarn add lodash
# NPM
$ npm install lodash --save
3.1 throttling 方法使用:
<template>
<button @click="throttledMethod()">Click me as fast as you can!</button>
</template>
<script>
import _ from 'lodash'
export default {
methods: {
throttledMethod: _.throttle(() => {
console.log('I get fired every two seconds!')
}, 2000)
}
}
</script>
3.2debouncing 方法使用
<template>
<button @click="throttledMethod()">Click me as fast as you can!</button>
</template>
<script>
import _ from 'lodash'
export default {
methods: {
throttledMethod: _.debounce(() => {
console.log('I only get fired once every two seconds, max!')
}, 2000)
}
}
</script>
4.react中使用
test = () => {
console.log('--------------11111---------------');
this.fun();//方法调用
}
//debounce使用
fun = _.debounce(function(e){
console.log('--------------22222---------------');
}, 5000,{
leading: true,
trailing: false,
})
//throttle使用
fun = _.throttle(function(e){
console.log('--------------22222---------------');
}, 5000,{
leading: true,
trailing: false,
})
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人