Skip to content

Instantly share code, notes, and snippets.

@gosukiwi
Created December 14, 2014 03:46
Show Gist options
  • Save gosukiwi/ba0eb9bce58abc49a5b5 to your computer and use it in GitHub Desktop.
Save gosukiwi/ba0eb9bce58abc49a5b5 to your computer and use it in GitHub Desktop.
Backbone's debounce
var debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var now = Date.now || function() {
return new Date().getTime();
};
var later = function() {
var last = now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment