Permalink
Browse files

Fixes #820 -- throttle function uses two timeouts.

  • Loading branch information...
1 parent 270c056 commit bb97a4d9f79712fed274f692a05a2828e1f8bba4 @jashkenas committed Oct 9, 2012
Showing with 16 additions and 16 deletions.
  1. +16 −16 underscore.js
View
@@ -622,25 +622,25 @@
// 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, result;
- var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
+ var context, args, timeout, result;
+ var previous = 0;
+ var later = function() {
+ previous = new Date;
+ timeout = null;
+ result = func.apply(context, args);
+ };
return function() {
- context = this; args = arguments;
- var later = function() {
- timeout = null;
- if (more) {
- result = func.apply(context, args);
- }
- whenDone();
- };
- if (!timeout) timeout = setTimeout(later, wait);
- if (throttling) {
- more = true;
- } else {
- throttling = true;
+ var now = new Date;
+ var remaining = wait - (now - previous);
+ context = this;
+ args = arguments;
+ if (remaining <= 0) {
+ clearTimeout(timeout);
+ previous = now;
result = func.apply(context, args);
+ } else if (!timeout) {
+ timeout = setTimeout(later, remaining);
}
- whenDone();
return result;
};
};

0 comments on commit bb97a4d

Please sign in to comment.