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


Lodash _.throttle()用法及代碼示例

Lodash是一個JavaScript庫,可在underscore.js之上運行。 Lodash幫助處理數組,字符串,對象,數字等。

lodash中的_.throttle()方法用於創建一個受限製的函數,該函數每個等待毫秒最多隻能調用一次func參數。這裏的節流函數具有一個cancel方法,該方法用於取消已延遲的函數調用,還具有flush方法,該方法用於立即調用該延遲的函數。此外,它提供了一些選項,這些選項用於暗示是否應在等待超時的前沿和/或後沿調用聲明的函數。

用法:

_.throttle(func, wait, options)

參數:該方法接受上述和以下所述的三個參數:

  • func:這是要限製的函數。
  • wait:它是要限製調用的毫秒數。
  • options:它是選項對象。
    • options.lead:它定義了超時前沿上的調用。
    • options.trailing:它在超時的後沿定義調用。

返回值:此方法返回新的限製函數。



注意:

  • 在這裏,func會被調用給最後被限製的函數。但是,對節流函數的後續調用將返回上一個func調用的結果。
  • 在此,如果前導和尾隨選項為true,則當且僅當在整個等待超時中多次調用受限製的函數時,才會在超時的後沿調用func。
  • 在此,如果等待時間為0,且前導選項為false,則func調用將延遲到下一個刻度。

範例1:

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Calling throttle() method with its parameter 
var throt_fun = _.throttle(function () { 
        console.log('Function throttled after 1000ms!'); 
    }, 1000); 
  
throt_fun();

輸出:在這裏,在1000ms之後調節函數後,這裏的等待時間是1000ms。

Function throttled after 1000ms!

範例2:

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Calling throttle() method with its parameter 
var throt_fun = _.throttle(function() { 
        console.log('Function throttled after 1000ms!'); 
    }, 1000); 
  
// Defining loop 
var loop = function() { 
    setTimeout(loop, 5) 
    throt_fun(); 
}; 
  
// Calling loop to start 
loop();

輸出:因此,直到您手動停止循環,循環才會停止。

Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
.
.
.
.
// So on until you stop it manually.

範例3:在此,該函數在超時的後沿被調用。

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Calling throttle() method with its parameter 
var throt_fun = _.throttle(function () { 
    console.log('Function is called on the'
        + ' trailing edge of the timeout '
        + 'and throttled after 2000ms!'); 
    }, 2000, { 'trailing':true }); 
  
throt_fun();

輸出:

Function is called on the trailing edge of the 
timeout and throttled after 2000ms!

參考:https://lodash.com/docs/4.17.15#throttle

相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Lodash _.throttle() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。