react 中使用 lodash 中的 _.throttle

1.场景:

首次调用执行一次,一定时间内再次调用,不再执行。

2.实现

debounce (函数去抖) 多次触发,只在最后一次触发时,执行目标函数。

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

throttle (函数节流)限制目标函数调用的频率,比如:1s内不能调用2次。

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

lodash在opitons参数中定义了一些选项,主要是以下三个:

leading,函数在每个等待时延的开始被调用,默认值为false

trailing,函数在每个等待时延的结束被调用,默认值是true

maxwait,最大的等待时间,因为如果debounce的函数调用时间不满足条件,可能永远都无法触发,因此增加了这个配置,保证大于一段时间后一定能执行一次函数

根据leading和trailing的组合,可以实现不同的调用效果:

leading-false,trailing-true:默认情况,即在延时结束后才会调用函数

leading-true,trailing-true:在延时开始时就调用,延时结束后也会调用

leading-true, trailing-false:只在延时开始时调用

deboucne还有cancel方法,用于取消防抖动调用

方式一:

test = () => {
  console.log('--------------11111---------------');
  this.fun();
}

fun = _.debounce(function(e){
  console.log('--------------22222---------------');
}, 5000,{
  leading: true,
  trailing: false,
})

首次点击时执行,连续点击且时间间隔在5s之内,不再执行,间隔在5s之外再次点击,执行。

方式二:

test = () => {
  console.log('--------------11111---------------');
  this.fun();
}

fun = _.throttle(function(e){
  console.log('--------------22222---------------');
}, 5000,{
  leading: true,
  trailing: false,
})

首次点击时执行,连续点击且间隔在5s之内,5s之后自动执行一次(注:连续点击次数时间之后小于5s,则不会自动执行),间隔在5s之外再次点击,执行。

.