From 73e6e87858fdbfa32fe8a41684be3ab6d01ae4d4 Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Mon, 2 Apr 2012 16:32:53 -0400 Subject: [PATCH] Fixes #465 -- throttled functions return their value when they actually run. --- test/functions.js | 11 +++++++---- underscore.js | 5 +++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/test/functions.js b/test/functions.js index 086233960..f8e5dc5c8 100644 --- a/test/functions.js +++ b/test/functions.js @@ -117,12 +117,15 @@ $(document).ready(function() { _.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 incr = function(){ counter++; }; + var incr = function(){ return ++counter; }; var throttledIncr = _.throttle(incr, 100); - throttledIncr(); - _.delay(function(){ equal(counter, 1, "incr was called once"); start(); }, 220); + var result = throttledIncr(); + _.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() { diff --git a/underscore.js b/underscore.js index 7d516cac7..72dc8e9f7 100644 --- a/underscore.js +++ b/underscore.js @@ -531,7 +531,7 @@ // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. _.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); return function() { context = this; args = arguments; @@ -544,10 +544,11 @@ if (throttling) { more = true; } else { - func.apply(context, args); + result = func.apply(context, args); } whenDone(); throttling = true; + return result; }; };