函數節流,簡單地講,就是讓一個函數無法在很短的時間間隔內連續調用,只有當上一次函數執行後過了你規定的時間間隔,才能進行下一次該函數的調用。
函數節流的原理挺簡單的,估計大家都想到了,那就是定時器。當我觸發一個時間時,先setTimout讓這個事件延遲一會再執行,如果在這個時間間隔內又觸發了事件,那我們就clear掉原來的定時器,再setTimeout一個新的定時器延遲一會執行,就這樣。
以下場景往往由於事件頻繁被觸發,因而頻繁執行DOM操作、資源加載等重行為,導致UI停頓甚至浏覽器崩潰。
1. window對象的resize、scroll事件
2. 拖拽時的mousemove事件
3. 射擊游戲中的mousedown、keydown事件
4. 文字輸入、自動完成的keyup事件
實際上對於window的resize事件,實際需求大多為停止改變大小n毫秒後執行後續處理;而其他事件大多的需求是以一定的頻率執行後續處理。針對這兩種需求就出現了debounce和throttle兩種解決辦法。
throttle 和 debounce 是解決請求和響應速度不匹配問題的兩個方案。二者的差異在於選擇不同的策略。
throttle 等時間 間隔執行函數。
debounce 時間間隔 t 內若再次觸發事件,則重新計時,直到停止時間大於或等於 t 才執行函數。
一、throttle函數的簡單實現
function throttle(fn, threshhold, scope) {
threshhold || (threshhold = 250);
var last,
timer; return function () {
var context = scope || this;
var now = +new Date(),
args = arguments;
if (last && now - last + threshhold < 0) {
// hold on to it
clearTimeout(deferTimer);
timer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};}
調用方法
$('body').on('mousemove', throttle(function (event)
{
console.log('tick');
}, 1000));
二、debounce函數的簡單實現
function debounce(fn, delay)
{
var timer = null;
return function ()
{
var context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};}
調用方法
$('input.username').keypress(debounce(function (event)
{
// do the Ajax request
}, 250));
三、簡單的封裝實現
/** * throttle * @param fn, wait, debounce */var throttle = function ( fn, wait, debounce ) {
var timer = null, // 定時器
t_last = null, // 上次設置的時間
context, // 上下文
args, // 參數
diff; // 時間差
return funciton () {
var curr = + new Date();
var context = this, args = arguments;
clearTimeout( timer );
if ( debounce ) { // 如果是debounce
timer = setTimeout( function () {
fn.apply( context, args );
}, wait );
} else { // 如果是throttle
if ( !t_last ) t_last = curr;
if ( curr - t_last >= wait ) {
fn.apply( context, wait );
context = wait = null;
}
} }}/** * debounce * @param fn, wait */var debounce = function ( fn, wait )
{
return throttle( fn, wait, true );
}
小結:這兩個方法適用於會重復觸發的一些事件,如:mousemove,keydown,keyup,keypress,scroll等。
如果只綁定原生事件,不加以控制,會使得浏覽器卡頓,用戶體驗差。為了提高js性能,建議在使用以上及類似事件的時候用函數節流或者函數去抖加以控制。
四、underscore v1.7.0相關的源碼剖析
1. _.throttle函數
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
// 定時器
var previous = 0;
// 上次觸發的時間
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function()
{
var now = _.now();
// 第一次是否執行
if (!previous && options.leading === false) previous = now;
// 這裡引入了一個remaining的概念:還剩多長時間執行事件
var remaining = wait - (now - previous);
context = this;
args = arguments;
// remaining <= 0 考慮到事件停止後重新觸發或者
// 正好相差wait的時候,這些情況下,會立即觸發事件
// remaining > wait 沒有考慮到相應場景
// 因為now-previous永遠都是正值,且不為0,那麼
// remaining就會一直比wait小,沒有大於wait的情況
// 估計是保險起見吧,這種情況也是立即執行
if (remaining <= 0 || remaining > wait)
{
if (timeout)
{
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
// 是否跟蹤
} else if (!timeout && options.trailing !== false)
{
timeout = setTimeout(later, remaining);
}
return result;
};};
由上可見,underscore考慮了比較多的情況:options.leading:
第一次是否執行,默認為true,表示第一次會執行,傳入{leading:false}則禁用第一次執行options.trailing:最後一次是否執行,默認為true,表示最後一次會執行,傳入{trailing: false}表示最後一次不執行所謂第一次是否執行,是剛開始觸發事件時,要不要先觸發事件,如果要,則previous=0,remaining 為負值,則立即調用了函數所謂最後一次是否執行,是事件結束後,最後一次觸發了此方法,如果要執行,則設置定時器,即事件結束以後還要在執行一次。remianing > wait 表示客戶端時間被修改過。
2. _.debounce函數
_.debounce = function(func, wait, immediate) {
// immediate默認為false
var timeout, args, context, timestamp, result;
var later = function() {
// 當wait指定的時間間隔期間多次調用_.debounce返回的函數,則會不斷更新timestamp的值,導致last < wait && last >= 0一直為true,從而不斷啟動新的計時器延時執行func var last = _.now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function()
{
context = this;
args = arguments;
timestamp = _.now();
// 第一次調用該方法時,且immediate為true,則調用func函數
var callNow = immediate && !timeout; // 在wait指定的時間間隔內首次調用該方法,則啟動計時器定時調用func函數
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};};
_.debounce實現的精彩之處我認為是通過遞歸啟動計時器來代替通過調用clearTimeout來調整調用func函數的延時執行。
以上所述是小編給大家介紹的JavaScript性能優化之函數節流(throttle)與函數去抖(debounce),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!