我正在寻找JS中的简单节流阀。我知道像lodash和underscore这样的库都有它,但是仅对一个函数来说,包含其中任何一个库都是过大的。
我也在检查jquery是否具有类似的功能-找不到。
我发现一个工作的节流阀,下面是代码:
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秒后仍会触发第二次按键。我不要这种行为。