From fd790566b25e278ae4107367d33cb5c2b17bd6ce Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Tue, 9 Oct 2012 02:11:41 -0700 Subject: [PATCH] Ensure `_.throttle` clears the timeout when `func` is called. [closes #86] Former-commit-id: 6f3b777aa247f059d97f965c02323d4ee6ab8464 --- lodash.js | 1 + test/test.js | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/lodash.js b/lodash.js index a69543cae9..3a6edb81aa 100644 --- a/lodash.js +++ b/lodash.js @@ -3468,6 +3468,7 @@ thisArg = this; if (remain <= 0) { + clearTimeout(timeoutId); lastCalled = now; result = func.apply(thisArg, args); } diff --git a/test/test.js b/test/test.js index a6d102219a..a5c5201c44 100644 --- a/test/test.js +++ b/test/test.js @@ -1597,6 +1597,31 @@ throttled(); }); + + asyncTest('should clear timeout when `func` is called', function() { + var now = new Date, + times = []; + + var throttled = _.throttle(function() { + times.push(new Date - now); + }, 20); + + setTimeout(throttled, 20); + setTimeout(throttled, 20); + setTimeout(throttled, 40); + setTimeout(throttled, 40); + + setTimeout(function() { + var actual = _.every(times, function(value, index) { + return index + ? (value - times[index - 1]) > 15 + : true; + }); + + ok(actual); + QUnit.start(); + }, 120); + }); }()); /*--------------------------------------------------------------------------*/