function customDebounce(func, wait) {
var args = [];
var timeoutId;
return function() {
// User formal parameters to make sure we add a slot even if a param
// is not passed in
if (func.length) {
for (var i = 0; i < func.length; i++) {
if (!args[i]) {
args[i] = [];
}
args[i].push(arguments[i]);
}
}
// No formal parameters, just track the whole argument list
else {
args.push(_.toArray(arguments));
}
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
func.apply(this, args);
args = [];
}, wait);
}
}
// For named arguments, each of the arguments becomes an array that tells
// you how many times it was called
var f = customDebounce(function(a, b, c) {
console.log('Debounced func called',
a.length,
'times', JSON.stringify({
a: a,
b: b,
c: c
}));
});
f(1, 3);
f(2, 3, 5);
f(3);
f(4, 2, 3);
// Debounced func called 4 times
// {"a":[1,2,3,4],"b":[3,3,null,2],"c":[null,5,null,3]}
// Can also be used with unnamed arguments, parameters are passed a little
// differently, each element in `arguments` is the array of arguments for
// that call, the latest one being at the end of the array
var g = customDebounce(function() {
console.log('Debounced no params func called ',
arguments.length,
'times',
JSON.stringify({
args: _.toArray(arguments)
}));
});
g(1, 3);
g(2, 3, 5);
g(3);
g(4, 2, 3);
// Debounced no params func called 4 times
// {"args":[[1,3],[2,3,5],[3],[4,2,3]]}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>