javascript - 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;
};
我无法想象“剩余”比“等待”更重要。这什么时候会发生?
解决方案
此条件处理在运行时更改系统时间的情况throttle
。
这看起来像是一个超级边缘案例,但实际上时间可能会改变有很多原因。您可以手动更改系统时间,也可以自动更改(例如由于与ntp server同步),您可以旅行并且您的时区已更改,当然,不要忘记DST。
我制作了一个游乐场,您可以在其中进行更深入的调查。
此提交中引入了此条件:允许 _.throttle 在系统时间更新后正常运行。
PS 我几乎在每个项目中都遇到了与时间相关的问题,我非常感谢所有这些思考这些事情的人。
推荐阅读
- bash - 将 mv 命令映射到每行文件和目录名称列表
- swift - Firebase Cloud Firestore - 从引用访问集合
- c++ - 无需修改目标分布的 Yocto 包生成(ARM 和 x86)
- javascript - 带有 OR 的 Vue.js v-if 无法正常工作
- excel - 密码仅保护 Excel VBA 中的某些工作表
- spring - Spring boot 2.2.4 spy bean集成测试不是Mockito mock
- sql - 将数据插入表后如何更新列的值
- python - PyQt 指令是如何进行的?
- r - 是否可以在 R 中测试是否存在指定的 `grDevices::windowsFonts` 并在测试失败时指定备份?
- javascript - 使用 Express 验证器版本 6.4.0 和快速上传。在执行路由发布之前检查输入验证