De-yu's Note
  • Deyu Notebook
  • Side Project
    • Stock
    • ChatBox
    • SnowCraft
    • ScrollBar
  • 架構問題
    • 解決 RTK Query data 為 undefined 的實務做法
    • 透過 xstate 解決UI 狀態問題
  • 技術觀點
    • 為什麼需要 store
    • Router 作用
    • react 和 next.js 差異
    • monoRepo vs Multiple Repo
  • Performance
    • React 優化
  • JS Coding
    • Curry
    • Debounce
    • Throttle
  • map
  • memo()
  • Promise 實作
  • Promise Function
  • Testing
    • 使用 Jest 、 React Testing Library 、MSW 建立測試環境
  • Miscellaneous
    • Event Loop
    • Browser
    • Code Review
    • Storage
  • AMD 、 CommonJS 、 ES modules
  • JWT
  • Next.js
  • 用過的 module
  • Internet
    • UDP
  • TCP/IP
  • SSL TLS
  • HTTP
  • AI 工作流
    • Page 1
Powered by GitBook
On this page
  1. JS Coding

Debounce


定義:將多次操作優化為,只在最後一次執行

使用情境:輸入框推薦

簡單版本

如果反覆的 call function 就重新計時
直到計時結束執行

function debounce(func, wait) {
  let id = 0;
  return (arg) => {
    clearTimeout(id);
    id = setTimeout(() => {
      func(arg)
    }, wait)
    
  }
}

有參數的版本


leading 控制最初的 function 觸發
trailing 控制結束的 function 觸發
兩個參數都 false 則不會有任何動作

function debounce(func, wait, option = {leading: false, trailing: true}) {

  let id = 0;
  let waiting = false;
  return (arg) => {

    if(!waiting && option.leading) { // 第一次 call func
      func(arg)
      waiting = true;
    } else {
      clearTimeout(id);
      id = setTimeout(() => {
        if(option.trailing) { // 結束 call func
          func(arg)
        }
        waiting = false;
      }, wait)
    }
  }
}
PreviousCurryNextThrottle

Last updated 28 days ago