首页 > 解决方案 > underscore.js 的油门实现中的“剩余 > 等待”条件语句何时为真?

问题描述

库代码(有问题的第 860 行): https ://github.com/jashkenas/underscore/blob/master/underscore.js

if (remaining <= 0 || remaining > wait)

下半场什么时候是真的?

背景 - 关于 SO 的第一篇文章,对 javascript 编码非常陌生。我已经从头开始重新实现油门作为练习,我正在将我的版本与库函数进行比较。我不明白为什么这部分条件语句存在于库函数中,因为在我看来它永远不会是真的,所以我认为我遗漏了一些东西。有人可以通过提供引用的陈述是真实的情况来填写我吗?

我已经通过调试器运行它并在谷歌上搜索文章但没有找到答案。

完整的库函数:

_.throttle = function(func, wait, options) {
    var timeout, context, args, result;
    var previous = 0;
    if (!options) options = {};

    var later = function() {
      previous = options.leading === false ? 0 : _.now();
      timeout = null;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    };

    var throttled = function() {
      var now = _.now();
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0 || remaining > wait) { // THIS LINE
        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;
    };

    throttled.cancel = function() {
      clearTimeout(timeout);
      previous = 0;
      timeout = context = args = null;
    };

    return throttled;
  };

我无法想象“剩余”比“等待”更重要。这什么时候会发生?

标签: javascriptunderscore.jsthrottling

解决方案


此条件处理在运行时更改系统时间的情况throttle

这看起来像是一个超级边缘案例,但实际上时间可能会改变有很多原因。您可以手动更改系统时间,也可以自动更改(例如由于与ntp server同步),您可以旅行并且您的时区已更改,当然,不要忘记DST

我制作了一个游乐场,您可以在其中进行更深入的调查。

此提交中引入了此条件:允许 _.throttle 在系统时间更新后正常运行

PS 我几乎在每个项目中都遇到了与时间相关的问题,我非常感谢所有这些思考这些事情的人。


推荐阅读