diff --git a/test/functions.js b/test/functions.js index 5bcf215b7..3df3e961e 100644 --- a/test/functions.js +++ b/test/functions.js @@ -118,6 +118,22 @@ $(document).ready(function() { _.delay(function(){ ok(value == 7, "updated to latest value"); start(); }, 400); }); + asyncTest("functions: throttle once", 1, function() { + var counter = 0; + var incr = function(){ counter++; }; + var throttledIncr = _.throttle(incr, 100); + throttledIncr(); + _.delay(function(){ ok(counter == 1, "incr was called once"); start(); }, 220); + }); + + asyncTest("functions: throttle twice", 1, function() { + var counter = 0; + var incr = function(){ counter++; }; + var throttledIncr = _.throttle(incr, 100); + throttledIncr(); throttledIncr(); + _.delay(function(){ ok(counter == 2, "incr was called twice"); start(); }, 220); + }); + asyncTest("functions: debounce", 1, function() { var counter = 0; var incr = function(){ counter++; }; diff --git a/underscore.js b/underscore.js index 60cf2ca8c..2462d767f 100644 --- a/underscore.js +++ b/underscore.js @@ -523,17 +523,21 @@ // 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; - var whenDone = _.debounce(function(){ throttling = false; }, wait); + var context, args, timeout, throttling, more; + var whenDone = _.debounce(function(){ more = throttling = false; }, wait); return function() { context = this; args = arguments; var later = function() { timeout = null; - func.apply(context, args); + if (more) func.apply(context, args); whenDone(); }; if (!timeout) timeout = setTimeout(later, wait); - if (!throttling) func.apply(context, args); + if (throttling) { + more = true; + } else { + func.apply(context, args); + } whenDone(); throttling = true; };