-
-
Save cwarden/6034893 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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(); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Latest version with tests is at https://github.com/cwarden/promising-debounce