Last active
December 22, 2015 06:18
-
-
Save chris-martin/6429958 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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