Skip to content

Instantly share code, notes, and snippets.

@BrandonBrowning
Last active January 3, 2016 15:19
Show Gist options
  • Save BrandonBrowning/8482007 to your computer and use it in GitHub Desktop.
Save BrandonBrowning/8482007 to your computer and use it in GitHub Desktop.
Simple throttle and debounce
// Transforms a function to throw away calls that occur within a timeframe after being called.
// ms: number - milliseconds to throw away /result/ calls after calling /f/
// f: function - wrapped with throttling behaivor as /result/
// result: function - throttled version of /f/
function throttle(ms, f) {
return function inner() {
if (!inner.throttle) {
f();
inner.throttle = setTimeout(function() {
inner.throttle = null;
}, ms);
}
}
}
// Transforms a function to not execute until a timeframe passes without being called.
// ms: number - milliseconds of no calls to /result/ until /f/ will be called
// f: function - wrapped with debounce behaivor as /result/
// result: function - debounced version of /f/
function debounce(ms, f) {
return function inner() {
if (inner.timeout) {
clearTimeout(inner.timeout);
inner.timeout = null;
}
inner.timeout = setTimeout(function() {
inner.timeout = null;
f();
}, ms);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment