当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Lodash _.debounce()用法及代码示例


Lodash是一个JavaScript库,可在underscore.js之上运行。 Lodash帮助处理数组,字符串,对象,数字等。

lodash中Function的_.debounce()方法用于创建一个反跳函数,该函数将给定的func延迟到自上次调用此反跳函数以来经过的指定等待时间(以毫秒为单位)之后。防反跳函数具有可用于取消延迟的函数调用的cancel方法和用于立即调用延迟的func的flush方法。

它还提供了一些选项,可用于暗示是否应在等待超时的前沿和/或后沿调用声明的函数。

注意:

  • 将使用给去抖动函数的最后一个参数来调用func。但是,对反跳函数的后续调用将返回上一个func调用的结果。
  • 当前导选项和尾随选项为true时,当且仅当在整个等待超时期间多次执行了去抖动函数时,才在超时的后沿调用func。
  • 当等待时间为0并且前导选项为false时,则func调用将推迟到下一个刻度。

用法:



_.debounce( func, wait, options )

参数:此方法接受上述和以下所述的三个参数:

  • func:该函数必须去抖动。
  • wait:这是调用将延迟的毫秒数。它是一个可选参数。默认值为0。
  • options:它是可用于更改方法行为的选项对象。它是一个可选参数。

options对象具有以下参数:

  • leading:它定义了超时前沿的调用。它是一个可选参数。默认值为false。
  • maxWait:它是函数被调用之前允许延迟的最大时间。它是一个可选参数。
  • trailing:它在超时的后沿定义调用。它是一个可选参数。默认值是true。

返回值:此方法返回新的去抖动函数。

范例1:在此示例中,由于等待时间为1000ms,因此可以在函数调用后1000m内再次输入REPL。

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Using _.debounce() method 
// with its parameters 
var debounce_fun = _.debounce(function () { 
  console.log('Function debounced after 1000ms!'); 
  }, 1000); 
  
debounce_fun();

输出:

Function debounced after 1000ms!

范例2:在此示例中,循环只有在手动停止后才会停止。

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Using _.debounce() method 
// with its parameters 
var debounce_fun = _.debounce(function() { 
  console.log('Function debounced after 1000ms!'); 
  }, 4, 1000, {'leading':false}); 
  
// Defining loop 
var loop = function() { 
    setTimeout(loop, 3) 
    debounce_fun(); 
}; 
  
// Calling loop to start 
loop();

输出:

Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
Function debounced after 1000ms!
.
.
.
.
// Will go on unless stopped manually

相关用法


注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 Lodash _.debounce() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。