lodash中节流(throttle)和防抖(debounce)

发布时间 2023-04-18 16:06:50作者: sk-xm

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,
})