Skip to content

Instantly share code, notes, and snippets.

@cwarden
Forked from swannodette/debounce.clj
Last active December 19, 2015 23:29
Show Gist options
  • Save cwarden/6034893 to your computer and use it in GitHub Desktop.
Save cwarden/6034893 to your computer and use it in GitHub Desktop.
/* Takes a function that optionally returns a promise, and debounces it, returning a
* promise to all callers. When the debounced function fulfills its promise or
* returns a non-promise, all callers get the result.
* Example: http://bit.ly/1btZC4f
*/
var debounce = function(func, wait, immediate) {
var timeout;
var deferred = $.Deferred();
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) {
$.when(func.apply(context, args))
.then(deferred.resolve, deferred.reject, deferred.notify);
deferred = $.Deferred();
}
};
var callNow = immediate && !timeout;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(later, wait);
if (callNow) {
deferred = $.Deferred();
$.when(func.apply(context, args))
.then(deferred.resolve, deferred.reject, deferred.notify);
}
return deferred.promise();
};
};
@cwarden
Copy link
Author

cwarden commented Jul 20, 2013

Latest version with tests is at https://github.com/cwarden/promising-debounce

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment