diff --git a/lodash.js b/lodash.js index 520d89b9a..f844ddb3c 100644 --- a/lodash.js +++ b/lodash.js @@ -4478,13 +4478,14 @@ */ function debounce(func, wait, options) { var args, + inited, result, thisArg, timeoutId, trailing = true; function delayed() { - timeoutId = null; + inited = timeoutId = null; if (trailing) { result = func.apply(thisArg, args); } @@ -4497,15 +4498,15 @@ trailing = 'trailing' in options ? options.trailing : trailing; } return function() { - var isLeading = leading && !timeoutId; args = arguments; thisArg = this; - clearTimeout(timeoutId); - timeoutId = setTimeout(delayed, wait); - if (isLeading) { + if (!inited && leading) { + inited = true; result = func.apply(thisArg, args); + } else { + timeoutId = setTimeout(delayed, wait); } return result; }; @@ -4706,10 +4707,9 @@ trailing = true; function trailingCall() { - lastCalled = new Date; timeoutId = null; - if (trailing) { + lastCalled = new Date; result = func.apply(thisArg, args); } } diff --git a/test/test.js b/test/test.js index 4850b21e6..0e3878b04 100644 --- a/test/test.js +++ b/test/test.js @@ -552,16 +552,29 @@ }, 64); }); - test('should work with `leading` option', function() { - _.each([true, { 'leading': true }], function(options) { - var withLeading = _.debounce(_.identity, 32, options); + asyncTest('should work with `leading` option', function() { + var counts = [0, 0, 0]; + _.each([true, { 'leading': true }], function(options, index) { + var withLeading = _.debounce(function(value) { + counts[index]++; + return value; + }, 32, options); + equal(withLeading('x'), 'x'); }); + _.times(2, _.debounce(function() { counts[2]++; }, 32, { 'leading': true })); + strictEqual(counts[2], 1); + _.each([false, { 'leading': false }], function(options) { var withoutLeading = _.debounce(_.identity, 32, options); strictEqual(withoutLeading('x'), undefined); }); + + setTimeout(function() { + deepEqual(counts, [1, 1, 2]); + QUnit.start(); + }, 64); }); asyncTest('should work with `trailing` option', function() {