Skip to content

Instantly share code, notes, and snippets.

@thehig
Last active December 7, 2020 07:37
Show Gist options
  • Save thehig/b0a9452077507db2b77b026444e60476 to your computer and use it in GitHub Desktop.
Save thehig/b0a9452077507db2b77b026444e60476 to your computer and use it in GitHub Desktop.
js: Aggregate Debounce
/*
Client wishes to emit a number of actions
Actions are identical RSAAs, with varying meta properties (usually the ID to request)
Ideal scenario
* Numerous actions are taken in within a timeout/debounce window
* After the timeout has expired, the actions are aggregated into a single API call
dispatch({
type: "SOME_FETCH_REQUEST",
payload: null,
meta: { id1 }
});
dispatch({
type: "SOME_FETCH_REQUEST",
payload: null,
meta: { id2 }
});
dispatch({
type: "SOME_FETCH_REQUEST",
payload: null,
meta: { id3 }
});
The middleware should consume these three actions and dispatch a single "SOME_FETCH_REQUEST" with meta { id1, id2, id3 }
*/
function aggregateDebounce(func, wait) {
var timeout;
var args = [];
return function() {
var context = this;
args = [].concat(args).concat(Array.from(arguments));
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
func.apply(context, [].concat(args));
args = [];
}, wait);
};
}
var counter = function(id){
var args = Array.from(arguments);
// console.log("Dispatch ", args);
console.log(args);
}
var debouncedCounter = aggregateDebounce(counter, 1000);
counter(1);
counter(2);
counter(3);
debouncedCounter(1);
debouncedCounter(2);
debouncedCounter(3, 3, 3);
debouncedCounter(4);
setTimeout(function(){
debouncedCounter(5, 5.5);
debouncedCounter(6);
}, 1200);
debouncedCounter(7);
debouncedCounter(8);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment