javascript – js中的简单油门
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – js中的简单油门,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2204字,纯文字阅读大概需要4分钟。
内容图文
![javascript – js中的简单油门](/upload/InfoBanner/zyjiaocheng/715/1e08e658200b453ea632e31c39efdc29.jpg)
我在JS寻找一个简单的油门.我知道像lodash和下划线这样的库有它,但只有一个函数包含任何这些库都是过度的.
我还在检查jquery是否有类似的功能 – 找不到.
I have found one working throttle,这是代码:
function throttle(fn, threshhold, scope) {
threshhold || (threshhold = 250);
var last,
deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
}
这个问题是:它在节流时间结束后再次激活该功能.所以让我们假设我在按键时每隔10秒发一个油门 – 如果我按下2次按键,它会在10秒完成时触发第二次按键.我不想要这种行为.
解决方法:
我会使用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:删除了对下划线的另一个引用,thx到Zettam的评论
编辑2:添加了关于lodash和可能的代码简化的建议,thx to lolzery wowzery的评论
内容总结
以上是互联网集市为您收集整理的javascript – js中的简单油门全部内容,希望文章能够帮你解决javascript – js中的简单油门所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。