首页 > web前端 > js教程 > 正文

以下是一些适合您文章内容的基于问题的标题: * **如何在 JavaScript 中实现简单的限制?** * **限制 JavaScript 函数的最佳方法是什么?** *

Mary-Kate Olsen
发布: 2024-10-25 08:54:28
原创
854 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!