Skip to content

Instantly share code, notes, and snippets.

@Soreine
Last active February 22, 2016 13:04
Show Gist options
  • Save Soreine/96981c07eb334d669036 to your computer and use it in GitHub Desktop.
Save Soreine/96981c07eb334d669036 to your computer and use it in GitHub Desktop.
A custom debouncing function
// Returns a function that can't be called more than once per `delay`,
// with a maximum delay of `maxDelay`. The returned function can be called
// forcefully through its `flush` property
function debounce(fn, delay, maxDelay) {
var timer;
var maxTimer;
var args;
var clearTimers = function () {
if (timer) clearTimeout(timer);
if (maxTimer) clearTimeout(maxTimer);
};
var doCallFn = function () {
clearTimers();
fn.apply(undefined, [].slice(args));
};
var debounced = function () {
args = arguments;
// Reset the timer
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(doCallFn, delay);
if (!maxTimer) {
maxTimer = setTimeout(doCallFn, maxDelay);
}
};
// Forces a call
debounced.flush = doCallFn;
return debounced;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment