Reputation: 285
When _.debounce is called multiple times, it only apply with the last call's argument.
var f = _.debounce(function(a) {
console.log(a);
})
f(12)
f(1223)
f(5)
f(42)
//output -----> 42
Is there a way to get previous function's call arguments as well ?
ex:
var f = _.customDebounce(function(a) {
console.log(a);
})
f(12)
f(1223)
f(5)
f(42)
//output -----> [12, 1223, 5, 42]
Upvotes: 4
Views: 2084
Reputation: 285
I finaly made my own implementation of this function, extending lodash:
_.mixin({
debounceArgs: function(fn, options) {
var __dbArgs = []
var __dbFn = _.debounce(function() {
fn.call(undefined, __dbArgs);
__dbArgs = []
}, options);
return function() {
__dbArgs.push(_.values(arguments));
__dbFn();
}
},
throttleArgs: function(fn, options) {
var _thArgs = []
var _thFn = _.throttle(function() {
fn.call(undefined, _thArgs);
_thArgs = []
}, options);
return function() {
_thArgs.push(_.values(arguments));
_thFn();
}
},
})
Usage:
_.debounceArgs(function(a) {
console.log(a);
})
Upvotes: 2
Reputation: 92274
Here's a simplistic debounce that tracks its arguments. It doesn't try to mimic the last parameter of _.debounce
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>
Upvotes: 0