Last active
January 3, 2016 15:19
-
-
Save BrandonBrowning/8482007 to your computer and use it in GitHub Desktop.
Simple throttle and debounce
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
// 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