定義:指定的時間間隔內只執行一次任務app
function Throttle(fn,delay){
let last,timer;
return function(){
let that = this;
let _args = arguments;
let now = +new Date();//等價 new Date().getTime()
if(last && now < last + delay){
clearTimeout(timer);
timer = setTimeout(function(){
last = now;
fn.apply(that,_args);
},delay)
}else {
last = now;
fn.apply(that,_args);
}
}
}
複製代碼
定義:在事件被觸發n秒後再執行回調,若是在這n秒內又被觸發,則從新計時函數
function debounce(fn,delay){
let timer = null;
return function(){
let that = this;
let _args = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
fn.applay(that,_args);
},delay)
}
}
複製代碼
1.輸入框進行搜索,用戶在不斷進行輸入的時候,不去請求,用防抖來節約請求資源; 2.window觸發resize的時候,會不斷觸發回調,用防抖來讓其只觸發一次this
1.鼠標不斷點擊觸發,或按鈕不斷被點擊觸發 2.監聽滾動事件,好比滾動到底部自動加載,用throttle判斷spa