DIV CSS 佈局教程網

淺談 JavaScript 函數節流(Throttle)
編輯:JavaScript基礎知識     

瀏覽器中某些運算與處理比其他操作昂貴得多。例如 DOM 操作比起非 DOM 互動需要更多記憶體與 CPU 時間,連續進行過多 DOM 操作可能導致瀏覽器掛起甚至崩潰。尤其在 IE 中使用 onresize 事件時,調整瀏覽器大小會連續觸發事件,若處理程序中頻繁操作 DOM,就可能讓瀏覽器崩潰。這正是函數節流的用武之地。

函數節流的基本思想

某些程式碼不可以在沒有間斷的情況下連續重複執行。第一次呼叫函數時建立一個計時器,在指定時間間隔後運行程式碼;第二次呼叫時會清除前一個計時器並重新設定一個。若前一個計時器已執行過,這個操作沒有意義;若尚未執行,則相當於將其替換為新計時器。目的是只有在執行請求停止了一段時間後才真正執行。

function throttle(method, context){
   clearTimeout(method.tId);
   method.tId = setTimeout(function(){
     method.call(context);
   }, 100);
}

應用範例

假設有一個 div 元素需要讓它的高度始終等於寬度:

function resizeDiv(){
   var div = document.getElementById("mydiv");
   div.style.height = div.offsetWidth + "px";
}
window.onresize = function(){
   throttle(resizeDiv);
}

這裡把調整大小的功能放進 resizeDiv 函數,再由 onresize 呼叫 throttle() 並傳入 resizeDiv,而非直接呼叫。多數情況下用戶感覺不到差別,但卻為瀏覽器省下了大量運算。

為什麼需要節流?

最常見的場景是螢幕伸縮 resize、touchmove 或 scroll 等事件。當我們使用:

$(window).resize(function(){
   console.log("window resize");
})

會發現只要稍微縮小視窗就會不停觸發。當 div 很多時,頁面不斷重繪,遇到版本較低的 IE 很可能導致瀏覽器崩潰。函數節流能有效避免這種情況。

物件方式的實作

var haoroomstest = {
   timeoutId: null,
   performProcessing: function(){
     console.log("resize");
   },
   process: function(){
     clearTimeout(this.timeoutId);
     var that = this;
     this.timeoutId = setTimeout(function(){
       that.performProcessing();
     }, 500)
   }
}
$(window).resize(function(){
   haoroomstest.process();
})

這樣就能減少請求、減少 DOM 重繪,達到節流目的。

其他常見寫法

方式一:函數掛屬性

function throttle(method, context){
   clearTimeout(method.tId);
   method.tId = setTimeout(function(){
     method.call(context);
   }, 100);
}
function resizeDiv(){ console.log("resize"); }
$(window).resize(function(){ throttle(resizeDiv); })

方式二:閉包返回函數

function throttle(method, delay){
   var timer = null;
   return function(){
     var context = this, args = arguments;
     clearTimeout(timer);
     timer = setTimeout(function(){
       method.apply(context, args);
     }, delay);
   }
}
function resizeDiv(){ console.log("resize"); }
window.onresize = throttle(resizeDiv, 500);

進階需求:兼顧觸發頻率

在做模糊搜尋智慧聯想提示時,會在 input 上綁定 keyup 事件,但不希望觸發得太頻繁。在方式二的基礎上稍作改動,加入 duration 參數控制最大觸發頻率:

function throttle(method, delay, duration){
   var timer = null, begin = new Date();
   return function(){
     var context = this, args = arguments, current = new Date();
     clearTimeout(timer);
     if(current - begin >= duration){
       method.apply(context, args);
       begin = current;
     } else {
       timer = setTimeout(function(){
         method.apply(context, args);
       }, delay);
     }
   }
}

透過函數節流,你能有效控制高頻事件的執行次數,讓頁面更流暢、更穩定。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved