當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。