Home >Web Front-end >JS Tutorial >How to Implement a Simple Throttle Function in JavaScript without External Libraries?

How to Implement a Simple Throttle Function in JavaScript without External Libraries?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 06:41:021080browse

How to Implement a Simple Throttle Function in JavaScript without External Libraries?

Simple Throttle in JavaScript without External Libraries

Introduction

In JavaScript, throttling is a technique used to limit the rate at which a function can be executed.

Custom Throttle Function

The provided custom throttle function, although functional, has a flaw in that it fires the function once more after the throttle time is complete. Here's a refined version:

<code class="js">function throttle(fn, wait, options) {
  if (!options) options = {};
  var context,
    args,
    result,
    timeout = null,
    previous = 0;
  var later = function () {
    previous = options.leading === false ? 0 : Date.now();
    timeout = null;
    result = fn.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 = fn.apply(context, args);
      if (!timeout) context = args = null;
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }
    return result;
  };
}</code>

This version addresses the issue with multiple triggering after the throttle period by implementing customizable options for leading and trailing edge behavior.

Simplified Throttle Function

If you don't need advanced options, a simplified, non-configurable throttle function is available:

<code class="js">function throttle(callback, limit) {
  var waiting = false;
  return function () {
    if (!waiting) {
      callback.apply(this, arguments);
      waiting = true;
      setTimeout(function () {
        waiting = false;
      }, limit);
    }
  };
}</code>

The above is the detailed content of How to Implement a Simple Throttle Function in JavaScript without External Libraries?. 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