簡體   English   中英

通過參數調用去抖函數

[英]Debounce function calls by their arguments

大衛沃爾什在這里有一個很好的去抖動實施。

// 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(eX)});

我很樂意經常觸發這個事件並且每秒調用處理程序甚至1000次。 我不需要去除處理程序本身。 但就我而言,對於每個eX,我希望在一段時間內只調用一次,比如250ms。

我正在考慮創建一個包含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 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(eX)

debounce(func_to_param, 250, 'mousewheel');
debounce(func_to_param, 250, 'scrolling');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM