Ensure _.debounce with leading and trailing will call the func on the leading edge after a trailing call is performed. [closes #257]

Former-commit-id: 97afe842b2b4c3eb20c9557298e01ec268386ea2
This commit is contained in:
John-David Dalton
2013-05-01 09:03:52 -07:00
parent 8f94bd1fbd
commit e773efdc59
2 changed files with 18 additions and 6 deletions

View File

@@ -4482,6 +4482,7 @@
*/ */
function debounce(func, wait, options) { function debounce(func, wait, options) {
var args, var args,
calledTwice,
inited, inited,
result, result,
thisArg, thisArg,
@@ -4489,8 +4490,9 @@
trailing = true; trailing = true;
function delayed() { function delayed() {
inited = timeoutId = null; var callTrailing = trailing && ((leading && calledTwice) || !leading);
if (trailing) { calledTwice = inited = timeoutId = null;
if (callTrailing) {
result = func.apply(thisArg, args); result = func.apply(thisArg, args);
} }
} }
@@ -4510,8 +4512,9 @@
inited = true; inited = true;
result = func.apply(thisArg, args); result = func.apply(thisArg, args);
} else { } else {
timeoutId = setTimeout(delayed, wait); calledTwice = true;
} }
timeoutId = setTimeout(delayed, wait);
return result; return result;
}; };
} }

View File

@@ -558,14 +558,19 @@
}); });
asyncTest('should work with `leading` option', function() { asyncTest('should work with `leading` option', function() {
var counts = [0, 0, 0]; var withLeadingAndTrailing,
counts = [0, 0, 0];
_.each([true, { 'leading': true }], function(options, index) { _.each([true, { 'leading': true }], function(options, index) {
var withLeading = _.debounce(function(value) { var debounced = _.debounce(function(value) {
counts[index]++; counts[index]++;
return value; return value;
}, 32, options); }, 32, options);
equal(withLeading('x'), 'x'); if (index == 1) {
withLeadingAndTrailing = debounced;
}
equal(debounced('x'), 'x');
}); });
_.times(2, _.debounce(function() { counts[2]++; }, 32, { 'leading': true })); _.times(2, _.debounce(function() { counts[2]++; }, 32, { 'leading': true }));
@@ -578,6 +583,10 @@
setTimeout(function() { setTimeout(function() {
deepEqual(counts, [1, 1, 2]); deepEqual(counts, [1, 1, 2]);
withLeadingAndTrailing('x');
equal(counts[1], 2);
QUnit.start(); QUnit.start();
}, 64); }, 64);
}); });