Skip to content
This repository
Browse code

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

  • Loading branch information...
commit cb8aff2631633def6275a9532476be347075b25d 1 parent c551884
Jeremy Ashkenas authored September 14, 2012
16  test/functions.js
@@ -141,7 +141,7 @@ $(document).ready(function() {
141 141
     var incr = function(){ return ++counter; };
142 142
     var throttledIncr = _.throttle(incr, 100);
143 143
     var results = [];
144  
-    var saveResult = function() { results.push(throttledIncr()); }
  144
+    var saveResult = function() { results.push(throttledIncr()); };
145 145
     saveResult(); saveResult(); saveResult();
146 146
     setTimeout(saveResult, 70);
147 147
     setTimeout(saveResult, 120);
@@ -159,7 +159,7 @@ $(document).ready(function() {
159 159
       equal(results[6], 2, "incr was throttled");
160 160
       equal(results[7], 3, "incr was called thrice");
161 161
       equal(results[8], 3, "incr was throttled");
162  
-      start();  
  162
+      start();
163 163
     }, 400);
164 164
   });
165 165
 
@@ -176,11 +176,17 @@ $(document).ready(function() {
176 176
     _.delay(function(){ equal(counter, 1, "incr was debounced"); start(); }, 220);
177 177
   });
178 178
 
179  
-  asyncTest("debounce asap", 2, function() {
  179
+  asyncTest("debounce asap", 5, function() {
  180
+    var a, b, c;
180 181
     var counter = 0;
181  
-    var incr = function(){ counter++; };
  182
+    var incr = function(){ return ++counter; };
182 183
     var debouncedIncr = _.debounce(incr, 50, true);
183  
-    debouncedIncr(); debouncedIncr(); debouncedIncr();
  184
+    a = debouncedIncr();
  185
+    b = debouncedIncr();
  186
+    c = debouncedIncr();
  187
+    equal(a, 1);
  188
+    equal(b, 1);
  189
+    equal(c, 1);
184 190
     equal(counter, 1, 'incr was called immediately');
185 191
     setTimeout(debouncedIncr, 30);
186 192
     setTimeout(debouncedIncr, 60);
7  underscore.js
@@ -613,17 +613,18 @@
613 613
   // N milliseconds. If `immediate` is passed, trigger the function on the
614 614
   // leading edge, instead of the trailing.
615 615
   _.debounce = function(func, wait, immediate) {
616  
-    var timeout;
  616
+    var timeout, result;
617 617
     return function() {
618 618
       var context = this, args = arguments;
619 619
       var later = function() {
620 620
         timeout = null;
621  
-        if (!immediate) func.apply(context, args);
  621
+        if (!immediate) result = func.apply(context, args);
622 622
       };
623 623
       var callNow = immediate && !timeout;
624 624
       clearTimeout(timeout);
625 625
       timeout = setTimeout(later, wait);
626  
-      if (callNow) func.apply(context, args);
  626
+      if (callNow) result = func.apply(context, args);
  627
+      return result;
627 628
     };
628 629
   };
629 630
 

0 notes on commit cb8aff2

Please sign in to comment.
Something went wrong with that request. Please try again.