Given a function fn and a time in milliseconds t, return a debounced version of that function.
給與一個函式 fn 和以毫秒為單位的時間 t,回傳防抖函式。 ex.debounce(防抖): 主要用於限制頻繁觸發的事情,並覆蓋前一次的需求。
A debounced function is a function whose execution is delayed by t milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also recieve the passed parameters.
防抖函式它的執行延遲了 t 毫秒,如果在再次呼叫它,它的執行將被取消。 防抖函式仍應該接收傳遞的參數。我們來看一個例子,假設 t = 50ms,函數在 30ms、60ms 和 100ms 被呼叫。 前 2 個函式呼叫將被取消,第 3 個函式呼叫將在 150 毫秒時執行。 相反,如果 t = 35ms,則第一個呼叫將被取消,第二個將在 95ms 執行,第三個將在 135ms 執行。
Example 1:
Input: t = 50 calls = [ {"t": 50, inputs: [1]}, {"t": 75, inputs: [2]} ] Output: [{"t": 125, inputs: [2]}]
Example 2:
Input: t = 20 calls = [ {"t": 50, inputs: [1]}, {"t": 100, inputs: [2]} ] Output: [{"t": 70, inputs: [1]}, {"t": 120, inputs: [2]}]
Example 3:
Input: t = 150 calls = [ {"t": 50, inputs: [1, 2]}, {"t": 300, inputs: [3, 4]}, {"t": 300, inputs: [5, 6]} ] Output: [{"t": 200, inputs: [1,2]}, {"t": 450, inputs: [5, 6]}]
solution:
宣告 debounce 函式用來限制某個函式在指定時間間隔內只執行一次。
當呼叫 debounce 函式時,它會清除之前設定的計時器並重新設定一個新的計時器。
只有在最後一次呼叫 debounce 函式後,計時器結束後才會執行傳入的函式。
ex. 例如處理使用者輸入、監聽事件。
Code 1: BigO(1)
var debounce = function(fn, t) { let timeout; return function(...args) { clearTimeout(timeout); timeout = setTimeout(() => { fn(...args) }, t); }; };
FlowChart:
Example 1
let start = Date.now(); function log(...inputs) { console.log([Date.now() - start, inputs ]) } const dlog = debounce(log, 50); setTimeout(() => dlog(1), 50); setTimeout(() => dlog(2), 75); //[ 126, [ 2 ] ]
Example 2
let start = Date.now(); function log(...inputs) { console.log([Date.now() - start, inputs ]) } const dlog = debounce(log, 20); setTimeout(() => dlog(1), 50); setTimeout(() => dlog(2), 100); //[ 71, [ 1 ] ] //[ 122, [ 2 ] ]
Example 3
let start = Date.now(); function log(...inputs) { console.log([Date.now() - start, inputs ]) } const dlog = debounce(log, 150); setTimeout(() => dlog(1, 2), 50); setTimeout(() => dlog(3, 4), 300); setTimeout(() => dlog(5, 6), 300); //[ 202, [ 1, 2 ] ] //[ 450, [ 5, 6 ] ]