1.概念
1.事件響應函數fn在等待一段時間之後纔會執行,如果在這個時間段內fn被再次調用,那麼會重新計算響應時間。
2. 使用節流的case:
1.輸入框查詢
2.表單驗證
3. 按鈕提交事件
4.scroll滾動事件
5.resize 事件
/**
* @description 節流
* @param fn 傳入的回調
* @param wait 間隔多少s執行
* @immediate 是否立即執行還是
*/
function debounce(fn, wait, immediate) {
let timer = null;
let res;
const debounceObj = function() {
let _this = this;
let args = arguments;
clearTimeout(timer);
// 立即執行
if(immediate) {
const callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, wait);
// 立即執行
if(callNow) {
res = fn.call(_this, ...args);
}
// 等待wait 以後才執行
} else {
timer = setTimeout(() => {
fn.call(_this, ...args);
}, wait);
}
return res;
}
debounce.cancel = function() {
clearTimeout(timer);
timer = null;
}
return debounceObj;
}
const dom = document.getElementsByClassName('move')[0];