Skip to content

Instantly share code, notes, and snippets.

@SgtPooki
Created June 18, 2015 20:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SgtPooki/21ffd584863d9cb1bd48 to your computer and use it in GitHub Desktop.
Save SgtPooki/21ffd584863d9cb1bd48 to your computer and use it in GitHub Desktop.
debounced promise
/*
Debounce promises.
Prevents multiple calls if the request is the same and either:
1. the promise has not resolved yet
2. a delay of {timeout} milliseconds has not passed since the last call
The call identity is dependent upon a key created with JSON.stringify(arguments)
*/
var debouncePromise = function debouncePromise(methodName, promise, throttleTimeout) {
var timeout = {};
var pendingPromise = {};
var isPromiseDone = {};
var isTimeoutDone = {};
var clearDebounceVariables = function clearDebounceVariables(cacheKey) {
delete isTimeoutDone[cacheKey];
delete isPromiseDone[cacheKey];
delete pendingPromise[cacheKey];
delete timeout[cacheKey];
};
var setCustomTimeout = function setCustomTimeout(cacheKey) {
clearTimeout(timeout[cacheKey]);
timeout[cacheKey] = setTimeout(function () {
isTimeoutDone[cacheKey] = true;
if (isPromiseDone[cacheKey]) {
clearDebounceVariables(cacheKey);
}
}, throttleTimeout);
};
return function debouncedPromise() {
var cacheKey = JSON.stringify(arguments);
if (pendingPromise[cacheKey]) {
setCustomTimeout(cacheKey);
console.log('Debouncing ' + methodName + ' that was called with ' + cacheKey);
return pendingPromise[cacheKey];
}
isPromiseDone[cacheKey] = false;
if (!throttleTimeout[cacheKey]) {
isTimeoutDone[cacheKey] = true;
} else {
setCustomTimeout(cacheKey);
}
pendingPromise[cacheKey] = promise.apply(null, arguments)
.then(function (result) {
isPromiseDone[cacheKey] = true;
if (isTimeoutDone[cacheKey]) {
clearDebounceVariables(cacheKey);
}
return result;
})
.catch(function (result) {
isPromiseDone[cacheKey] = true;
if (isTimeoutDone[cacheKey]) {
clearDebounceVariables(cacheKey);
}
return result;
});
return pendingPromise[cacheKey];
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment