當前位置:
首頁 > 知識 > 函數節流(throttle)與函數去抖(debounce)

函數節流(throttle)與函數去抖(debounce)

頻繁執行一段JS邏輯代碼對性能會有很大的影響,比如監聽 resize、scroll、mousemove等事件,並作出相應的DOM操作,或者邏輯中需要進行後端請求,此時會發現每移動一定像素便觸發了大量的回調函數,回調函數中又伴隨著DOM操作,或者後端請求,繼而引發瀏覽器的重排與重繪,性能差的瀏覽器可能會直接假死。為此,需要降低觸發回調的頻率,而函數節流(throttle)與函數去抖(debounce)是在時間軸上控制函數的執行次數。

函數防抖(debounce):在事件觸發 n 秒後再執行回調,如果這 n 秒內又被觸發,則重新計時。

例如:實現對於輸入框連續輸入進行AJAX驗證。

沒有去抖之前:

function ajax(content){

console.log("ajax request " + content);

}

var input = document.getElementById("input");

input.addEventListener("keyup", function(e){ajax(e.target.value)})

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

此時每按一個鍵就會觸發一次 ajax 請求。現在用debounce方法改進:

function ajax(content){

console.log("ajax request " + content);

}

function debounce(func, delay){

return function(args){

var _this = this,

_args = args;

clearTimeout(func.id);

func.id = setTimeout(func.call(_this, _args),delay);

}

}

var debounceAjax = debounce(ajax, 1000);

var input = document.getElementById("input");

input.addEventListener("keyup", function(e){debunounceAjax(e.target.value)})

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

此時,並不是每按一個鍵就會觸發 ajax 請求,而是當停止輸入並在指定時間內沒有輸入的時候,才會執行相應的回調函數。

函數節流(throttle):規定一個單位時間,在這個單位時間內,只能有一次觸發事件的回調函數執行,如果在同一個單位時間內某個事件被觸發多次,只有一次能生效。

例如:繼續上面的例子,使用throttle方法改進:

function ajax(content){

console.log("ajax request " + content);

}

function throttle(func, delay){

var last, deferTimer;

return function(){

var _this = this,

_args = arguments,

now = +new Date();

if(last && now < last + delay){

clearTimeout(deferTimer);

deferTimer = setTimeout(function(){

last = now;

func.apply(_this, _args);

}, delay);

} else {

last = now;

func.apply(_this._args);

}

}

}

var throttleAjax = throttle(ajax, 1000);

var input = document.getElementById("input");

input.addEventListener("keyup", function(e){throttleAjax(e.target.value)})

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

此時,ajax回調是每隔1s執行一次。

函數節流(throttle)與函數去抖(debounce)

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

8 個有力的 Awk 內建變數
spring boot 2.0 經過半月使用給出階段性總結

TAG:程序員小新人學習 |