Skip to content

Commit

Permalink
Merge pull request jashkenas#1269 from rhysbrettbowen/master
Browse files Browse the repository at this point in the history
add in single timeout implementation of debounce
  • Loading branch information
jashkenas committed Sep 7, 2013
2 parents 66282d0 + 9e0a92a commit 19ab4e4
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -690,17 +690,24 @@
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var result;
var timeout = null;
var timeout, args, context, timestamp, result;
return function() {
var context = this, args = arguments;
context = this;
args = arguments;
timestamp = new Date();
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
var last = (new Date()) - timestamp;
if (last < wait) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow) result = func.apply(context, args);
return result;
};
Expand Down

0 comments on commit 19ab4e4

Please sign in to comment.