首頁  >  文章  >  web前端  >  以下是一些適合您文章內容的基於問題的標題: * **如何在 JavaScript 中實現簡單的限制? * **限制 JavaScript 函數的最佳方法是什麼? *

以下是一些適合您文章內容的基於問題的標題: * **如何在 JavaScript 中實現簡單的限制? * **限制 JavaScript 函數的最佳方法是什麼? *

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-25 08:54:28855瀏覽

Here are a few question-based titles that fit the content of your article:

* **How Can I Implement Simple Throttling in JavaScript?** 
* **What's the Best Way to Throttle a JavaScript Function?**
* **Need to Prevent Overwhelm? Here's How to Throttle Yo

JavaScript 中的簡單限制

在JavaScript 中,限制是一種將函數的執行限制在特定時間間隔的技術。當您想要避免過多的函數呼叫使系統不堪重負時,這非常有用。

現有的節流實作

像 lodash 和 underscore 這樣的函式庫提供內建的節流函數。然而,為一個簡單的任務包含這些整個庫可能是多餘的。

自訂節流函數

這是一個可以用作獨立解決方案的自訂節流函數:

<code class="javascript">function throttle(fn, threshhold, scope) {
  threshhold || (threshhold = 250);
  var last,
      deferTimer;
  return function () {
    var context = scope || this;

    var now = +new Date,
        args = arguments;
    if (last &amp;&amp; now < last + threshhold) {
      // hold on to it
      clearTimeout(deferTimer);
      deferTimer = setTimeout(function () {
        last = now;
        fn.apply(context, args);
      }, threshhold);
    } else {
      last = now;
      fn.apply(context, args);
    }
  };
}

改進:避免重複執行

但是,所提供的程式碼存在一個問題,即一旦限制時間間隔過去,它可能會再次觸發該函數。為了解決這個問題,我們可以修改函數如下:

<code class="javascript">function throttle(fn, threshhold, scope) {
  threshhold || (threshhold = 250);
  var last,
      deferTimer;
  return function () {
    var context = scope || this;

    var now = +new Date;
    if (now < last + threshhold) {
      return; // prevent subsequent execution
    }

    last = now;
    fn.apply(context, arguments);
  };
}

進階節流函數

為了獲得更多的靈活性和更多選項,您可以參考以下實作:

<code class="javascript">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 &amp;&amp; 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;
  };
};</code>

以上是以下是一些適合您文章內容的基於問題的標題: * **如何在 JavaScript 中實現簡單的限制? * **限制 JavaScript 函數的最佳方法是什麼? *的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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