David Walsh has a great debounce implementation here.
// 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);
    };
};
I am using it in production and it works great.
Now i have encountered a bit more complex case of debounce need.
I have an event that calls an event handler with a param like this: $(elem).on('onSomeEvent', (e) => {handler(e.X)} );
I am ok with this event being triggered frequently and calling the handler even 1000 times a second. I don't need to debounce the handler itself. But in my case, for each e.X, i want it to be called just once in a period, say 250ms.
I was thinking of creating a two dimensional array which holds the x and the last run time, but i don't want to declare any global variables.
Any ideas?
* EDIT *
After reading @Tim Vermaelen answer i have implemented it like this, and it worked:
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);
        };
    };
                What I always use is the following:
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
I don't believe there's much difference with your solution except for the fact I can add unique id's in the events. You'll have to wrap this around handler(e.X) if I understand correctly.
debounce(func_to_param, 250, 'mousewheel');
debounce(func_to_param, 250, 'scrolling');
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With