Home  >  Article  >  Web Front-end  >  ## Why Do JavaScript Throttle Functions Sometimes Fire Once More After the Throttle Time Has Elapsed?

## Why Do JavaScript Throttle Functions Sometimes Fire Once More After the Throttle Time Has Elapsed?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 03:27:28572browse

##  Why Do JavaScript Throttle Functions Sometimes Fire Once More After the Throttle Time Has Elapsed?

JavaScript Throttle Function

Introduction

JavaScript throttling is a useful technique that can prevent functions from being executed too frequently. This can be particularly beneficial in situations where excessive function calls can cause performance issues or unintended effects.

Custom Throttle Functions

The following JavaScript code provides a reusable "throttle" function:

<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);
    }
  };
}

Revised Throttling Function

However, the provided function has a notable drawback. After the throttle time has elapsed, it fires the function one more time. This can lead to undesired behavior in certain scenarios.

A revised version of the throttling function is available from libraries such as underscore.js and lodash. This version effectively addresses the issue of firing the function after the throttle time:

<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>

Simplified Throttle Function

A simplified, non-configurable version of the throttling function is provided below:

<code class="javascript">function throttle (callback, limit) {
    var waiting = false;                      // Initially, we're not waiting
    return function () {                      // We return a throttled function
        if (!waiting) {                       // If we're not waiting
            callback.apply(this, arguments);  // Execute users function
            waiting = true;                   // Prevent future invocations
            setTimeout(function () {          // After a period of time
                waiting = false;              // And allow future invocations
            }, limit);
        }
    }
}</code>

With this function, you can control the frequency of function executions by adjusting the "limit" parameter.

The above is the detailed content of ## Why Do JavaScript Throttle Functions Sometimes Fire Once More After the Throttle Time Has Elapsed?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn