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