From cb8aff2631633def6275a9532476be347075b25d Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Fri, 14 Sep 2012 16:39:35 -0400 Subject: [PATCH] Fixes #740 -- debounced functions now return their last updated value --- test/functions.js | 16 +++++++++++----- underscore.js | 7 ++++--- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/test/functions.js b/test/functions.js index 43aab1073..a52965877 100644 --- a/test/functions.js +++ b/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); diff --git a/underscore.js b/underscore.js index 90032d973..797c40b07 100644 --- a/underscore.js +++ b/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; }; };