首頁  >  文章  >  web前端  >  **為什麼簡單的JavaScript節流函數會消除節流期後的最終執行? **

**為什麼簡單的JavaScript節流函數會消除節流期後的最終執行? **

DDD
DDD原創
2024-10-27 00:41:30483瀏覽

**Why does the Simple JavaScript Throttle Function Eliminate the Final Execution After the Throttle Period?**

JavaScript 中的簡單節流

JavaScript 提供了各種用於節流功能的工具,包括 lodash 和 underscore。然而,對於這些庫可能過多的情況,自訂節流實作是可取的。

現有節流功能和挑戰

提供的節流功能是功能性的,但是它提出了一個問題。節流期結束後,它最後一次執行函數。在該函數不應多次觸發的情況下,這可能會導致出現不必要的行為。

改進的節流函數

要解決此問題,請考慮以下增強的節流函數:消除節流週期後的最終執行:

function throttle(func, wait, options) {
  var context, args, result;
  var timeout = null;
  var previous = 0;
  if (!options) options = {};
  var later = function() {
    previous = options.leading === false ? 0 : Date.now();
    timeout = null;
    result = func.apply(context, args);
    if (!timeout) context = args = null;
  };
  return function() {
    var now = Date.now();
    if (!previous && options.leading === false) previous = now;
    var remaining = wait - (now - previous);
    context = this;
    args = arguments;
    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 &amp;&amp; options.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }
    return result;
  };
};

此更新的函數提供了一個可配置的節流機制,帶有用於前沿和後沿觸發的可選參數。

簡化的節流功能

如果不需要可自訂性,更簡單的節流函數如下:

function throttle (callback, limit) {
    var waiting = false; 
    return function () { 
        if (!waiting) { 
            callback.apply(this, arguments); 
            waiting = true; 
            setTimeout(function () { 
                waiting = false; 
            }, limit);
        }
    }
}

這個不可設定的函數將目標函數節流到指定的時間間隔,而不需要複雜的選項.

以上是**為什麼簡單的JavaScript節流函數會消除節流期後的最終執行? **的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn