Jeff的隨手筆記

學習當一個前端工程師

0%

『菜鳥的踩坑筆記』- Throttle 與 Debounce 的差異

前言

這是上一篇「Race condition 的認識與解法」的衍伸篇章,也是我在技術分享會上有介紹到的主題。考慮到資料都已整理好,決定與大家分享這些實用的前端優化技術。

為什麼介紹 Race condition 會延伸出 Throttle 與 Debounce,最主要的原因是就是我在研究 Race condition 解決方案時,我發現使用 AbortController 的方法在某些情境下與 Debounce 概念非常相似。為了確認自己的想法是對是錯,所以才又去驗證自己的想法,這邊就把這 3 種做一個簡單的比較吧

Throttle 與 Debounce 介紹

Throttle (節流)

  • 目的:限制函式在一定時間內只能執行一次
  • 特點:
    • 持續性執行
    • 固定時間間隔
  • 應用場景:視窗滾動事件、需要穩定執行的操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function throttle(fn, delay = 500) {
let timer = null;

return function (...args) {
// 如果 timer 存在,表示在 delay 時間內,直接返回
if (timer) return;

// 設定計時器
timer = setTimeout(() => {
timer = null;
}, delay);

// 執行函式
fn.apply(this, args);
};
}

// 如果一直滑動畫面,會固定 500ms console.log('throttle')
const updateThrottleText = throttle(() => {
console.log("throttle");
}, 500);

window.addEventListener("scroll", () => {
updateThrottleText();
});

Debounce (防抖)

  • 目的:延遲執行,多次觸發只執行最後一次
  • 特點:
    • 等待期間可被重置
    • 最後一次觸發後才執行
  • 應用場景:搜尋輸入、表單提交
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function debounce(fn, delay = 500) {
let timer;

return (...args) => {
// 清除之前的 timer
clearTimeout(timer);

// 設定新的 timer
timer = setTimeout(() => {
fn(...args);
}, delay);
};
}

// updateDebounceText 會在延遲 500 ms 後執行 console.log('call api get search result')
const updateDebounceText = debounce((text) => {
console.log("call api get search result");
}, 500);

searchInput.addEventListener("input", (e) => {
updateDebounceText(e.target.value);
});

實作區別

  • Throttle:
    • 使用單一 timer 控制執行頻率
    • 確保一段時間內只執行一次
    • 適合需要固定頻率執行的場景
  • Debounce:
    • 每次觸發都會重置 timer
    • 只有在最後一次觸發後的延遲時間才執行
    • 適合需要等待使用者操作完成的場景

總結

研究完這三種技術後,我忍不住笑了出來 — 當初腦袋是裝了什麼啊,居然覺得解 Race condition 的 AbortController 方法會跟 Debounce 是一樣的?這個奇妙的連結害我又得多寫一篇技術文章 XD

雖然多花了時間整理文章(這個主題資料很多),但這個過程讓我對這些技術邊界有了更清晰的認識。原來它們是不同情境下的解決方案,各自有自己的舞台呢!

真的很感謝自己那個愛問自己「為什麼」的個性(但又不愛問人,還好現在有 AI 可以問),至少避免了我在技術討論會上說出「Race condition 可以用 Debounce 解決」這種讓大家翻白眼的話!

希望這篇文章對正在爬前端坑的同伴們有幫助。別像我一樣搞混這些概念

參考資源

https://kettanaito.com/blog/debounce-vs-throttle

https://medium.com/@steven234/throttle%E8%B7%9F-debounce%E6%9C%89%E4%BB%80%E9%BA%BC%E5%8D%80%E5%88%A5-e0b1979b1b4f

https://medium.com/@bs903944/debounce-and-throttling-what-they-are-and-when-to-use-them-eadd272fe0be