(深入理解)debounce 與 throttle 的時間模型與 this 流動
debounce throttle this
debounce throttle this
debounce throttle this
...
今天本來只是想複習 debounce / throttle 手寫,結果一路從「會寫」直接鑽到「時間模型 + this 機制」,這種越學越深的感覺其實滿爽的 😂
起點:只是想搞懂 debounce / throttle
一開始的理解其實很單純:
1 | debounce → 停下來才做 |
但寫著寫著就開始卡:
- 為什麼 throttle 有兩種寫法?
- timer vs timestamp 差在哪?
- 為什麼要 last = now?
- this 為什麼會壞?
throttle 的關鍵突破:時間基準
最重要的理解在這裡👇
1 | if (now - last >= delay) { |
一開始不懂為什麼要:
1 | last = now; |
後來想通:
1 | 👉 last 是「上一次執行的時間」 |
用自己的話記:
1 | 每次執行 → 把時間基準往前更新 |
throttle 本質(今天最關鍵收穫)
1 | throttle 不是固定排程 |
也就是:
1 | ✔ 至少間隔 delay 才能執行 |
debounce vs throttle(用 timer 角度理解)
這個理解超清楚👇
1 | debounce → timer 是「延後執行」 |
對應 code:
1 | // debounce |
this 問題(今天第二個大坑)
卡在這句:
1 | return function (...args) { |
為什麼不能用 arrow?
核心理解
1 | function → this 看呼叫 |
debounce 裡的結構
1 | return function (...args) { |
👉 關鍵:
1 | 外層 function → 拿呼叫時的 this |
更深一層:arrow function 的陷阱
如果 fn 是 arrow:
1 | debounce(300, () => { |
👉 就會壞掉:
1 | ❌ this 無法被 apply 改 |
👉 得出結論:
1 | 不用 this → 用 arrow |
Vue2 vs Vue3 的聯想(意外收穫)
今天突然串起來:
1 | Vue2 → this 驅動 |
Vue2
1 | this.submit(); |
👉 很依賴 this
Vue3
1 | submit(); |
👉 完全不用 this
👉 所以:
1 | debounce + function 很像 Vue2 |
Event Loop 小補充
順便補了:
1 | setTimeout(fn, 0) ≠ 立即執行 |
今天最重要的三句話
1 | 1. debounce 是「延後執行」 |
心得(真實記錄)
一開始只是想複習題目,結果一路挖到:
- timer vs timestamp
- event loop
- this 綁定
- Vue 設計差異
有點像在拆一個很大的系統,每一層都連在一起。
下一步
1 | - 把 throttle(leading + trailing)合併寫法搞懂 |
收尾一句
1 | 這題不是在寫 function |