Skip to content

Instantly share code, notes, and snippets.

@sozidatel
Created March 15, 2015 18:16
Show Gist options
  • Save sozidatel/897bca154358baac4533 to your computer and use it in GitHub Desktop.
Save sozidatel/897bca154358baac4533 to your computer and use it in GitHub Desktop.
Extended debounce function with methods inProgress(), cancel() & applyImmediate()
var sozDebouncer = function (func, wait) {
if (typeof func != 'function') {
throw new TypeError;
}
wait = Math.max(parseInt(wait, 10) || 0, 0);
var timer;
var thisArg;
var args;
var debouncedFunc = function () {
thisArg = this;
args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
func.apply(thisArg, args);
timer = null;
}, wait)
};
debouncedFunc.inProgress = function () {
return timer ? true : false;
};
debouncedFunc.applyImmediate = function () {
if (this.inProgress()) {
this.cancel();
func.apply(thisArg, args);
}
};
debouncedFunc.cancel = function () {
if (this.inProgress()) {
clearTimeout(timer);
}
};
return debouncedFunc;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment