JavaScript 中的简单节流阀 [英] Simple throttle in JavaScript

查看:37
本文介绍了JavaScript 中的简单节流阀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个简单的 JavaScript 节流器.我知道像 lodash 和 underscore 这样的库都有它,但仅对于一个函数来说,包含这些库中的任何一个都太过分了.

I am looking for a simple throttle in JavaScript. I know libraries like lodash and underscore have it, but only for one function it will be overkill to include any of those libraries.

我也在检查 jQuery 是否有类似的功能 - 找不到.

I was also checking if jQuery has a similar function - could not find.

我找到了一个工作节流阀,这是代码:

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

这样做的问题是:它在油门时间完成后再次触发该功能.所以让我们假设我做了一个每 10 秒在按键时触发的油门 - 如果我按键 2 次,它仍然会在 10 秒完成后触发第二个按键.我不想要这种行为.

The problem with this is: it fires the function once more after the throttle time is complete. So let's assume I made a throttle that fires every 10 seconds on keypress - if I do keypress 2 times, it will still fire the second keypress when 10 seconds are completed. I do not want this behavior.

推荐答案

我会使用 underscore.jslodash 源代码以找到经过良好测试的版本这个功能.

I would use the underscore.js or lodash source code to find a well tested version of this function.

这是下划线代码的略微修改版本,用于删除对 underscore.js 本身的所有引用:

Here is the slightly modified version of the underscore code to remove all references to underscore.js itself:

// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
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 && options.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }
    return result;
  };
};

请注意,如果您不需要所有强调支持的选项,可以简化此代码.

Please note that this code can be simplified if you don't need all the options that underscore support.

请在下面找到此功能的一个非常简单且不可配置的版本:

Please find below a very simple and non-configurable version of this function:

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

编辑 1:删除了对下划线的另一个引用,感谢@Zettam 的评论

Edit 1: Removed another reference to underscore, thx to @Zettam 's comment

编辑 2:添加了关于 lodash 和可能的代码简化的建议,感谢@lolzery @wowzery 的评论

Edit 2: Added suggestion about lodash and possible code simplification, thx to @lolzery @wowzery 's comment

编辑 3:由于流行的请求,我添加了一个非常简单的、不可配置的函数版本,改编自 @vsync 的评论

Edit 3: Due to popular requests, I added a very simple, non-configurable version of the function, adapted from @vsync 's comment

这篇关于JavaScript 中的简单节流阀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆