📜  Lodash _.debounce() 方法

📅  最后修改于: 2022-05-13 01:56:29.670000             🧑  作者: Mango

Lodash _.debounce() 方法

Lodash是一个基于 underscore.js 的 JavaScript 库。 Lodash 有助于处理数组、字符串、对象、数字等。

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

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

笔记:

  • 使用提供给去抖动函数的最后一个参数调用func 。但是,对 debounced函数的后续调用会返回最后一次func调用的结果。
  • 当前导和尾随选项为真时,当且仅当在整个等待超时期间多次调用去抖动函数时,才会在超时的后沿调用func
  • 当等待时间为 0 且前导选项为 false 时,函数调用将延迟到下一个刻度。

句法:

_.debounce( func, wait, options )

参数:此方法接受三个参数,如上所述,如下所述:

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

选项对象具有以下参数:

  • 领先:它定义了在超时前沿的调用。它是一个可选参数。默认值为假。
  • 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();


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!

示例 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