我正在寻找一个简单的JavaScript节流函数。我知道类库,如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 秒触发一次的节流器,如果我按下按键两次,当 10 秒结束时它仍然会触发第二次按键。我不希望这种行为发生。
tree-shaking
功能,你仍然可以像这样使用导入:import throttle from 'lodash/throttle'
。这样,只会导入一个函数。 - Shivam Jha