Skip to content

Instantly share code, notes, and snippets.

@larryprice
Last active November 17, 2015 19:32
Show Gist options
  • Save larryprice/56d0091815d79db390af to your computer and use it in GitHub Desktop.
Save larryprice/56d0091815d79db390af to your computer and use it in GitHub Desktop.
How does _'s debounce work?
var _ = {};
_.debounce = function (func, wait, immediate) {
var timeout, start, that, args;
var later = function () {
if (Date.now() - start >= wait && !immediate) {
func.apply(that, args);
timeout = null;
}
};
return function () {
start = new Date();
that = this;
args = arguments;
if (immediate && !timeout) func.apply(that, args);
if (!timeout) timeout = setTimeout(later, wait);
};
}
var f = function (str) {
console.log(str);
};
var debouncedF = _.debounce(f, 500);
debouncedF(1);
debouncedF(2);
debouncedF(3);
debouncedF(4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment