diff --git a/lodash.js b/lodash.js index 3a22ac98b..99435a94b 100644 --- a/lodash.js +++ b/lodash.js @@ -4482,6 +4482,7 @@ */ function debounce(func, wait, options) { var args, + calledTwice, inited, result, thisArg, @@ -4489,8 +4490,9 @@ trailing = true; function delayed() { - inited = timeoutId = null; - if (trailing) { + var callTrailing = trailing && ((leading && calledTwice) || !leading); + calledTwice = inited = timeoutId = null; + if (callTrailing) { result = func.apply(thisArg, args); } } @@ -4510,8 +4512,9 @@ inited = true; result = func.apply(thisArg, args); } else { - timeoutId = setTimeout(delayed, wait); + calledTwice = true; } + timeoutId = setTimeout(delayed, wait); return result; }; } diff --git a/test/test.js b/test/test.js index 11b23cb1b..4ba65ce10 100644 --- a/test/test.js +++ b/test/test.js @@ -558,14 +558,19 @@ }); 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) { - var withLeading = _.debounce(function(value) { + var debounced = _.debounce(function(value) { counts[index]++; return value; }, 32, options); - equal(withLeading('x'), 'x'); + if (index == 1) { + withLeadingAndTrailing = debounced; + } + equal(debounced('x'), 'x'); }); _.times(2, _.debounce(function() { counts[2]++; }, 32, { 'leading': true })); @@ -578,6 +583,10 @@ setTimeout(function() { deepEqual(counts, [1, 1, 2]); + + withLeadingAndTrailing('x'); + equal(counts[1], 2); + QUnit.start(); }, 64); });