Skip to content

Instantly share code, notes, and snippets.

@reu
Last active December 22, 2015 23:19
Show Gist options
  • Save reu/6546038 to your computer and use it in GitHub Desktop.
Save reu/6546038 to your computer and use it in GitHub Desktop.
Returns a function that as long as it continues to be called, it will not be invoked. It will only be called after `time` milliseconds.
function debounce(fn, time) {
var time = time || 300,
scope = this,
delay;
return function() {
var args = arguments;
if (delay) clearTimeout(delay);
delay = setTimeout(function() {
fn.apply(scope, args);
}, time);
}
}
$("input").on("keyup", debounce(function() {
$.get("/search", { query: $(this).val() }, updateSearchResults);
}));
var callTimes = 0;
function fn() {
callTimes += 1;
if (callTimes > 1) console.assert(false, "Expected only one call, but was called "+ callTimes +" times");
}
var debouncedFn = debounce(fn, 0);
debouncedFn();
debouncedFn();
debouncedFn();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment