Skip to content

Instantly share code, notes, and snippets.

@chris-martin
Last active December 22, 2015 06:18
Show Gist options
  • Save chris-martin/6429958 to your computer and use it in GitHub Desktop.
Save chris-martin/6429958 to your computer and use it in GitHub Desktop.
/*
Wraps `f` such that the resulting function can be invoked at most once per `milliseconds`.
The first invocation has the same effect and return value as `f`. Subsequent invocations
within the buffer timeframe have the same return value as `f` but do not side effect.
Note that `f` should not be recursive. If `f` recurses, the return value of this function
will be `undefined`.
*/
function debounce(f, milliseconds) {
milliseconds = milliseconds || 1000;
var buffer;
return function () {
if (!buffer) {
buffer = {};
buffer.value = f.apply(this, arguments);
buffer.timeout = setTimeout(
function () {
buffer = undefined;
},
milliseconds
);
}
return buffer.value;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment