通过参数去抖动函数调用

Dor*_*rad 6 javascript events debouncing

David Walsh在这里有一个很好的去抖动实现。

// 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);
    };
};
Run Code Online (Sandbox Code Playgroud)

我在生产中使用它,效果很好。

现在我遇到了一个更复杂的去抖动需求案例。

我有一个事件,它使用这样的参数调用事件处理程序: $(elem).on('onSomeEvent', (e) => {handler(eX)} );

我对这个事件被频繁触发并每秒调用处理程序的次数感到满意 1000 次。我不需要去抖动处理程序本身。但就我而言,对于每个 eX,我希望它在一段时间内只被调用一次,比如 250 毫秒。

我正在考虑创建一个保存 x 和上次运行时间的二维数组,但我不想声明任何全局变量。

有任何想法吗?

* 编辑 *

在阅读@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);
        };
    };
Run Code Online (Sandbox Code Playgroud)

Tim*_*len 5

我一直使用的是以下内容:

var debounce = (function () {
    var timers = {};

    return function (callback, delay, id) {
        delay = delay || 500;
        id = id || "duplicated event";

        if (timers[id]) {
            clearTimeout(timers[id]);
        }

        timers[id] = setTimeout(callback, delay);
    };
})(); // note the call here so the call for `func_to_param` is omitted
Run Code Online (Sandbox Code Playgroud)

除了我可以在事件中添加唯一 ID 之外,我认为您的解决方案没有太大区别。handler(e.X)如果我理解正确,您必须将其环绕。

debounce(func_to_param, 250, 'mousewheel');
debounce(func_to_param, 250, 'scrolling');
Run Code Online (Sandbox Code Playgroud)