Skip to content

Instantly share code, notes, and snippets.

@alexeyraspopov

alexeyraspopov/debounce.js

Last active Nov 19, 2019
Embed
What would you like to do?
/**
* @example
* let refetch = debounce((params) => makeRequest('/api', params));
* let prA = refetch(paramsA);
* let prB = refetch(paramsB);
* let prC = refetch(paramsC);
* let prD = refetch(paramsD);
* (prA === prB === prC === prD)
* awaits the last promise
*/
function debounce(fn) {
let head = null;
let current = null;
return (...args) => {
let promise = fn(...args);
current = promise;
if (!head) {
head = deferred();
}
promise.then(
value => {
if (current === promise) {
head.resolve(value);
head = null;
}
},
error => {
if (current === promise) {
head.reject(error);
head = null;
}
}
);
return head.promise;
};
}
function deferred() {
let resolve = null;
let reject = null;
let promise = new Promise((rslv, rjct) => {
resolve = rslv;
reject = rjct;
});
return { promise, resolve, reject };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment