- 函數防抖(debounce),在連續的操作中,無論進行了多長時間,只有某一次的操作后在指定的時間內沒有再操作,這一次才被判定有效(類似電腦10分鍾后休眠)。如模糊搜索,輸入框內容一直變化,會導致一直發送請求。防抖即輸入內容完成后,一定時間(比如500ms)沒有再輸入內容,這時再觸發請求。
- ts版
<el-input v-model="keyWord" placeholder="默認拼音模糊搜索" style="width: 300px;" @keydown.native='SearchData'></el-input>
keyWord='';//檢索關鍵詞
SearchData;//屬性(放函數對象)
public async mounted() {
this.loading = true;
this.SearchData=this.debounce(this.SearchDataFn,800);//無論觸發多少次,都只會在800毫秒后執行查詢代碼
await this.SearchData();//查詢數據
this.loading = false;
}
//防抖
debounce(fn, wait) {
let timer = null;
let that = this;
return function () {
let arg = arguments;
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(null, arg)
}, wait);
}
}
async SearchDataFn(){
//ts代碼編寫的調用查詢webapi
}
function Demo(e){
console.log(this);
console.log(e);
}
function debounce(fn,wait){
let timer=null;
return function(){
if(timer!==null){
clearTimeout(timer);
}
timer=setTimeout(()=>{
fn.apply(this,arguments)
},wait);
}
}
let Demo1=debounce(Demo,300);
- 節流,規定時間內,只觸發一次。如用快捷鍵提交表單,如果1s內多次觸發快捷鍵,就會重復提交。每次發送請求,會給服務器造成巨大的壓力,但是我們進行節流后,就會大大減少請求的次數。
<script>
var timer1;
function throttle(fn, delay) {
if (timer1) {
return;
}
timer1 = setTimeout(function () {
fn();
timer1 = null;
},delay);
}
function testThrettle() {
console.log('js節流');
}
document.onmousemove = () => {
throttle(testThrettle, 10);
}
</script>