通过参数去除函数调用的抖动

7

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);
    };
};

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

现在我遇到了一个稍微复杂一些的防抖需求。

我有一个事件,调用一个带参数的事件处理程序,如下所示: $(elem).on('onSomeEvent', (e) => {handler(e.X)} );

我可以接受这个事件频繁地触发并调用处理程序,即使每秒钟调用1000次。我不需要对处理程序本身进行防抖动。 但在我的情况下,对于每个 e.X,我希望它在一段时间内只被调用一次,比如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);
        };
    };

原始代码中var timeout也不是全局变量吗? - Bergi
似乎很不幸 - Dorad
不是不幸,而是正好你想要的吗? - Bergi
显然,这使得工作变得容易 - Dorad
1个回答

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

我认为除了我可以在事件中添加唯一的ID之外,你的解决方案并没有太大区别。如果我理解正确,你需要将其包装在handler(e.X)周围。
debounce(func_to_param, 250, 'mousewheel');
debounce(func_to_param, 250, 'scrolling');

1
我现在正在尝试,等我尝试完会告诉你。 - Dorad
1
运行得非常好。我将我的修改发布给其他人。 - Dorad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接