在前端的性能優化中,我們經常會聽到有一個叫做防抖和節流的技術。
所謂的防抖就是當事件頻繁連續觸發的時候,我們不做處理,當事件的觸發間隔大於我們設定的時間時,我們再去觸發這個事件,如此就減少了事件的觸發頻率,而節流的思路則是不管事件觸發的頻率如何,我們都在指定的時間間隔內僅僅觸發一次事件,說了這麼多嗎,我覺得還是看代碼比較實在
防抖
function Debounce(fn, time){
let timer = null;
return function(){
let context = this,
args = arguments;
if(timer) clearTimeout(timer);
timer = setTimeout(function(){
fn.apply( context, args);
}, time);
}
}
節流
function Throttling(fn, time){
let timer = null;
return function(){
let context = this,
args = arguments;
if(!timer){
timer = setTimeout(function(){
fn.apply(context, args);
timer = null;
});
}
}
}
具體的效果可以觀去這個地址查看 https://alizwell.github.io/front-end/JS/DebounceThrottling.html