Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Fixes #740 -- debounced functions now return their last updated value

  • Loading branch information...
commit cb8aff2631633def6275a9532476be347075b25d 1 parent c551884
@jashkenas authored
Showing with 15 additions and 8 deletions.
  1. +11 −5 test/functions.js
  2. +4 −3 underscore.js
View
16 test/functions.js
@@ -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);
@@ -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);
});
@@ -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);
View
7 underscore.js
@@ -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;
};
};
Please sign in to comment.
Something went wrong with that request. Please try again.