在短期屢次觸發某個函數的場景下,對執行函數進行節流,節省無效浪費javascript
1. 使用場景php
export function debounce(fun, delay){
let timer //定時器
return function (...args){
if (timer) {
clearTimeout(timer)
}
timer = setTimerout(() => { //
fun.apply(this, args)
}, delay)
}
}
複製代碼
注:代碼來源vue-music音樂播放器項目vue
2. 函數調用java
this.$watch(
"query",
debounce(newQuery => {
// 不超過200ms函數節流
this.$emit("query", newQuery);
}, 200)
);
複製代碼
this.$emit("query", newQuery);
前給函數加個節流函數3. 誤區git
博客原文地址
項目地址:vue-music音樂播放器項目github