栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

js中的简单节流阀

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

js中的简单节流阀

我将使用underscore.js或lodash源代码找到该功能的经过良好测试的版本。

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

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

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

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

编辑2:在lollzery wowzery的评论中添加了有关lodash和可能的代码简化的建议



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/575135.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号