Created
June 18, 2015 20:27
-
-
Save SgtPooki/21ffd584863d9cb1bd48 to your computer and use it in GitHub Desktop.
debounced promise
This file contains 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
/* | |
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