【问题标题】:How to make a pure JS anology of lodash throttle leading如何制作 lodash 油门领先的纯 JS 类比
【发布时间】:2018-02-25 15:24:15
【问题描述】:

谁能告诉我制作纯 JS anology 的方法是什么:

window.addEventListener('scroll', _.throttle(callback, 500, { leading: true, trailing: false}));

【问题讨论】:

  • 查看 lodashs 源代码。

标签: javascript lodash


【解决方案1】:

希望对你有帮助

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

window.addEventListener('scroll', throttle(callback, 500, { leading: true, trailing: false}));

【讨论】:

  • 吉比!谢谢,但是为什么这不起作用?请在这里查看我的示例并告诉我我做错了什么:jsfiddle.net/3pk1op97
  • @zocihi 因为你正在添加一个滚动监听器,但是你的页面不够长,不能滚动来做滚动,尝试添加.target { height: 1000px } as css 来添加滚动到页面,你可以看到@ 987654322@,我刚刚添加了css
  • 天哪!我对这一切都很陌生,但这太酷了! xD 谢谢!
【解决方案2】:

这里是来源:https://github.com/lodash/lodash/blob/master/throttle.js

function throttle(func, wait, options) {
  let leading = true
  let trailing = true

  if (typeof func != 'function') {
    throw new TypeError('Expected a function')
  }
  if (isObject(options)) {
    leading = 'leading' in options ? !!options.leading : leading
    trailing = 'trailing' in options ? !!options.trailing : trailing
  }
  return debounce(func, wait, {
    'leading': leading,
    'maxWait': wait,
    'trailing': trailing
  })
}

参考这里的 debounce - https://github.com/lodash/lodash/blob/master/debounce.js

【讨论】:

  • 所以我需要在之前导入 debounce 吗?在此之前我还需要导入 isObject.js 和 root.js 吗?如果没有所有这些不必要的东西,我怎样才能让它独立存在?
  • 在这种情况下,只需参考这个,独立版本的油门,https://github.com/niksy/throttle-debounce/blob/master/throttle.js
猜你喜欢
  • 2022-08-11
  • 2020-12-05
  • 2019-05-22
  • 2021-01-01
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 2015-11-29
  • 2020-11-11
相关资源
最近更新 更多