underscore的防抖函数,难题

新手上路,请多包涵

在界面中添加一个按钮。immediate设置为false,wait设置为1000.连点两下按钮,later函数会被调用。这是为啥呢?我设置的超时时间为1000,还没到时间呢,为啥later会被触发执行呢?
underscore这个库的防抖函数实现如下。

  var timeout, previous, args, result, context;

  var later = function () {
    var passed = now() - previous;
    console.log('passed', passed)
    if (passed < wait) {
      console.log('later被调用,但是还有' + (wait - passed) + "时间,才能调用")
      timeout = setTimeout(later, wait - passed);
    } else {
      console.log('clear timeout and call our func')
      timeout = null;
      if (!immediate) result = func.apply(context, args);
      // This check is needed because `func` can recursively invoke `debounced`.
      if (!timeout) args = context = null;
    }
  };

  var debounced = restArguments(function (_args) {
    context = this;
    args = _args;
    previous = now();
    console.log('debounce timeout', timeout)
    if (!timeout) {
      console.log('------------')
      timeout = setTimeout(later, wait);
      if (immediate) result = func.apply(context, args);
    }
    return result;
  });
阅读 1.4k
2 个回答
新手上路,请多包涵

这样连点两次,test在不到1秒的时候,就会执行。为什么呢?

    onClick() {
      this.callback();
    },
    test() {
      console.log("test func", Date.now() - this.p);
      this.timeout = null;
    },
    callback() {
      this.p = Date.now();
      if (!this.timeout) {
        this.timeout = setTimeout(this.test, 1000);
      }
    },

你的问题一开始没看懂,你自己添加了一个回答,那个回答里面的代码时间计算是有问题的。
当你在一秒钟内点击两下,每一下都会更新你的this.p参数,意味着,当你在500ms点击第二下的时候this.p记录了最后一次的时间,所以时间计算当然不准

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题