Skip to content

Commit

Permalink
Fixes jashkenas#740 -- debounced functions now return their last upda…
Browse files Browse the repository at this point in the history
…ted value
  • Loading branch information
jashkenas committed Sep 14, 2012
1 parent c551884 commit cb8aff2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
16 changes: 11 additions & 5 deletions test/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ $(document).ready(function() {
var incr = function(){ return ++counter; };
var throttledIncr = _.throttle(incr, 100);
var results = [];
var saveResult = function() { results.push(throttledIncr()); }
var saveResult = function() { results.push(throttledIncr()); };
saveResult(); saveResult(); saveResult();
setTimeout(saveResult, 70);
setTimeout(saveResult, 120);
Expand All @@ -159,7 +159,7 @@ $(document).ready(function() {
equal(results[6], 2, "incr was throttled");
equal(results[7], 3, "incr was called thrice");
equal(results[8], 3, "incr was throttled");
start();
start();
}, 400);
});

Expand All @@ -176,11 +176,17 @@ $(document).ready(function() {
_.delay(function(){ equal(counter, 1, "incr was debounced"); start(); }, 220);
});

asyncTest("debounce asap", 2, function() {
asyncTest("debounce asap", 5, function() {
var a, b, c;
var counter = 0;
var incr = function(){ counter++; };
var incr = function(){ return ++counter; };
var debouncedIncr = _.debounce(incr, 50, true);
debouncedIncr(); debouncedIncr(); debouncedIncr();
a = debouncedIncr();
b = debouncedIncr();
c = debouncedIncr();
equal(a, 1);
equal(b, 1);
equal(c, 1);
equal(counter, 1, 'incr was called immediately');
setTimeout(debouncedIncr, 30);
setTimeout(debouncedIncr, 60);
Expand Down
7 changes: 4 additions & 3 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -613,17 +613,18 @@
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout;
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
if (callNow) result = func.apply(context, args);
return result;
};
};

Expand Down

0 comments on commit cb8aff2

Please sign in to comment.