From d5e2489cadafa60feb2c012017597e864e9460bf Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Tue, 1 May 2012 21:13:02 -0400 Subject: [PATCH] lodash: Make `deb ounce` match `throttle`'s return value behavior. [jddalton] Former-commit-id: 2d4073c8a2ba20b98344c19cbfaf388a2683ef19 --- lodash.js | 24 ++++++++++++++---------- test/test.js | 13 +++++++++++++ 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/lodash.js b/lodash.js index bf9909ece..e4e94aa56 100644 --- a/lodash.js +++ b/lodash.js @@ -1558,16 +1558,16 @@ } /** - * Creates a new function that will delay its execution until after `wait` - * milliseconds have elapsed since the last time it was invoked. Pass `true` - * for `immediate` to cause debounce to invoke the function on the leading, + * Creates a new function that will delay the execution of `func` until after + * `wait` milliseconds have elapsed since the last time it was invoked. Pass + * `true` for `immediate` to cause debounce to invoke `func` on the leading, * instead of the trailing, edge of the `wait` timeout. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to debounce. - * @param {Number} wait The number of milliseconds to postone. + * @param {Number} wait The number of milliseconds to delay. * @param {Boolean} immediate A flag to indicate execution is on the leading * edge of the timeout. * @returns {Function} Returns the new debounced function. @@ -1577,26 +1577,30 @@ * jQuery(window).on('resize', lazyLayout); */ function debounce(func, wait, immediate) { - var args, thisArg, timeout; + var args, + result, + thisArg, + timeoutId; function delayed() { - timeout = undefined; + timeoutId = undefined; if (!immediate) { func.apply(thisArg, args); } } return function() { - var isImmediate = immediate && !timeout; + var isImmediate = immediate && !timeoutId; args = arguments; thisArg = this; - clearTimeout(timeout); - timeout = setTimeout(delayed, wait); + clearTimeout(timeoutId); + timeoutId = setTimeout(delayed, wait); if (isImmediate) { - func.apply(thisArg, args); + result = func.apply(thisArg, args); } + return result; }; } diff --git a/test/test.js b/test/test.js index 047b85e84..07988749b 100644 --- a/test/test.js +++ b/test/test.js @@ -99,6 +99,19 @@ /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.debounce'); + + (function() { + test('subsequent "immediate" debounced calls should return the result of the first call', function() { + var debounced = _.debounce(function(value) { return value; }, 100, true), + result = [debounced('x'), debounced('y')]; + + deepEqual(result, ['x', 'x']); + }); + }()); + + /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.forEach'); (function() {