Last active
December 7, 2020 07:37
-
-
Save thehig/b0a9452077507db2b77b026444e60476 to your computer and use it in GitHub Desktop.
js: Aggregate Debounce
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
/* | |
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