David Walsh 拥有出色的去抖动实现here https://davidwalsh.name/javascript-debounce-function.
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
我在生产中使用它并且效果很好。
现在我遇到了一些更复杂的去抖需求情况。
我有一个事件调用带有如下参数的事件处理程序:
$(elem).on('onSomeEvent', (e) => {handler(e.X)} );
我可以接受频繁触发此事件并每秒调用处理程序 1000 次。我不需要对处理程序本身进行反跳。
但就我而言,对于每个 e.X,我希望它在一个周期内仅被调用一次,比如 250 毫秒。
我正在考虑创建一个二维数组来保存 x 和最后一次运行时间,但我不想声明任何全局变量。
有任何想法吗?
* EDIT *
阅读@Tim Vermaelen 的回答后,我已经像这样实现了它,并且它有效:
export function debounceWithId(func, wait, id, immediate?) {
var timeouts = {};
return function () {
var context = this, args = arguments;
var later = function () {
timeouts[id] = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeouts[id];
clearTimeout(timeouts[id]);
timeouts[id] = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};