[實現API] Debouce

Randy Liu
1 min readMay 22, 2023

--

The _.debounce() method of Function in lodash is used to create a debounced function which delays the given func until after the stated wait time in milliseconds have passed since the last time this debounced function was called.

const debounce = function(func, time) {
// 先將timer存在HOF
let timer = null;

return function(...args) {
// 若已有timer,清除,不然背景會繼續進行
if(timer !== null) {
clearTimeout(timer);
timer = null;
}

// 將context存起來
let context = this;

// 繼續宣告timeout
timer = setTimeout(() => {
// 將context以及參數都帶進去
func.apply(context, args);
}, time)
}
}

const func = (...args) => {
console.log("function runs with args:" + args);
// 看看click event結束後到函數被執行過了幾秒
console.log("time pasts from click event ends: " + (Date.now() - now));
}

// 宣告被debounce包裝後的函數,並將time射程1秒
const debounced = debounce(func, 1000)

// 模仿click event
// 模仿每100ms按一次
// 記錄時間加以觀察

let clickedCount = 0, now = Date.now();

let clickEvent = setInterval(() => {
console.log("clicked")

debounced(1, 2, 3)

// 按到地20下清除click event
if(++clickedCount === 20) {
console.log("clicked event ends: " + (Date.now() - now))
now = Date.now();

clearInterval(clickEvent);
clickEvent = null;
}
}, 100)

--

--