Created
June 12, 2015 18:05
-
-
Save prestonp/9a8b379043357ef2f045 to your computer and use it in GitHub Desktop.
debounce
This file contains 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
var debounce = function(fn, interval) { | |
var lock = false; | |
var id; | |
return function debouncedFn() { | |
var args = arguments; | |
var invoke = function() { | |
lock = false; | |
fn.apply(null, args); | |
} | |
// Reset invocation if called within interval | |
if (lock) { | |
clearTimeout(id); | |
id = setTimeout(invoke, interval); | |
return; | |
} | |
// Lock and apply function | |
id = setTimeout(invoke, interval); | |
lock = true; | |
} | |
} | |
var debouncedPrint = debounce(console.log.bind(console), 2000); | |
debouncedPrint('poop'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment