From 35c6db12899c116dc2767e699a0855add0891bc7 Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Tue, 20 Oct 2015 21:49:01 -0700 Subject: [PATCH] Add `flush` to debounced methods. --- lodash.js | 17 +++++++++++++---- test/test.js | 27 +++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/lodash.js b/lodash.js index 342244c03..0742c8175 100644 --- a/lodash.js +++ b/lodash.js @@ -7904,10 +7904,10 @@ * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel - * delayed invocations. Provide an options object to indicate that `func` - * should be invoked on the leading and/or trailing edge of the `wait` timeout. - * Subsequent calls to the debounced function return the result of the last - * `func` invocation. + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide an options object to indicate that `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. Subsequent calls to the + * debounced function return the result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked * on the trailing edge of the timeout only if the the debounced function is @@ -8020,6 +8020,14 @@ } } + function flush() { + if ((timeoutId && trailingCall) || (maxTimeoutId && trailing)) { + result = func.apply(thisArg, args); + } + cancel(); + return result; + } + function maxDelayed() { complete(trailing, timeoutId); } @@ -8066,6 +8074,7 @@ return result; } debounced.cancel = cancel; + debounced.flush = flush; return debounced; } diff --git a/test/test.js b/test/test.js index abf1b8ae5..2f3765aaa 100644 --- a/test/test.js +++ b/test/test.js @@ -18732,6 +18732,33 @@ done(); } }); + + QUnit.test('_.' + methodName + ' should support flushing delayed calls', function(assert) { + assert.expect(2); + + var done = assert.async(); + + if (!(isRhino && isModularize)) { + var callCount = 0; + + var funced = func(function() { + return ++callCount; + }, 32, { 'leading': false }); + + funced(); + var actual = funced.flush(); + + setTimeout(function() { + assert.strictEqual(actual, 1); + assert.strictEqual(callCount, 1); + done(); + }, 64); + } + else { + skipTest(assert, 2); + done(); + } + }); }); /*--------------------------------------------------------------------------*/