安裝依賴
npm i throttle-debounce-ts
區別:
- 函數節流在特定時間內觸發一次任務,並且是規律的
- 函數防抖只有最后一次延時時間到達之后執行一次
應用場景:
- throttle
- 鼠標不斷點擊觸發,mousedown(單位時間內只觸發一次)
- 監聽滾動事件,比如是否滑到底部自動加載更多,用throttle來判斷
- debounce
- 百度搜索,用戶在不斷輸入值時,用防抖來節約請求資源。
- window觸發resize的時候,不斷的調整瀏覽器窗口大小會不斷的觸發這個事件,用防抖來讓其只觸發一次
lodash 的 節流(throttle) 和 防抖(debounce)
例:每隔300毫秒執行一次 onConfigDialogClick函數
<el-button type="primary" @click="saveDebounce">確 定</el-button> //引用 import { throttle} from 'throttle-debounce-ts'; //使用 private saveDebounce = throttle(300, this.onConfigDialogClick); // 點擊確定按鈕 onConfigDialogClick() { const verifyResult = this.templateEditer.formVerifyResult(); if (verifyResult !== '') { this.$message.warning(verifyResult); return; } //請求數據 this.onRequestDataChanged(); }
例:在停止點擊300毫秒后,調用onConfigDialogClick方法
<el-button type="primary" @click="saveDebounce">確 定</el-button> //引用 import { debounce } from 'throttle-debounce-ts'; //使用 private saveDebounce = debounce(300, this.onConfigDialogClick); // 點擊確定按鈕 onConfigDialogClick() { const verifyResult = this.templateEditer.formVerifyResult(); if (verifyResult !== '') { this.$message.warning(verifyResult); return; } //請求數據 this.onRequestDataChanged(); }