Fixes #465 -- throttled functions return their value when they actually run.

This commit is contained in:
Jeremy Ashkenas
2012-04-02 16:32:53 -04:00
parent 1366d90333
commit 73e6e87858
2 changed files with 10 additions and 6 deletions

View File

@@ -117,12 +117,15 @@ $(document).ready(function() {
_.delay(function(){ equal(value, 6, "updated to latest value"); start(); }, 400); _.delay(function(){ equal(value, 6, "updated to latest value"); start(); }, 400);
}); });
asyncTest("functions: throttle once", 1, function() { asyncTest("functions: throttle once", 2, function() {
var counter = 0; var counter = 0;
var incr = function(){ counter++; }; var incr = function(){ return ++counter; };
var throttledIncr = _.throttle(incr, 100); var throttledIncr = _.throttle(incr, 100);
throttledIncr(); var result = throttledIncr();
_.delay(function(){ equal(counter, 1, "incr was called once"); start(); }, 220); _.delay(function(){
equal(result, 1, "throttled functions return their value");
equal(counter, 1, "incr was called once"); start();
}, 220);
}); });
asyncTest("functions: throttle twice", 1, function() { asyncTest("functions: throttle twice", 1, function() {

View File

@@ -531,7 +531,7 @@
// Returns a function, that, when invoked, will only be triggered at most once // Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. // during a given window of time.
_.throttle = function(func, wait) { _.throttle = function(func, wait) {
var context, args, timeout, throttling, more; var context, args, timeout, throttling, more, result;
var whenDone = _.debounce(function(){ more = throttling = false; }, wait); var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
return function() { return function() {
context = this; args = arguments; context = this; args = arguments;
@@ -544,10 +544,11 @@
if (throttling) { if (throttling) {
more = true; more = true;
} else { } else {
func.apply(context, args); result = func.apply(context, args);
} }
whenDone(); whenDone();
throttling = true; throttling = true;
return result;
}; };
}; };