Created
September 10, 2015 12:43
-
-
Save asuraphel/cabc9680fe2fc48dfd00 to your computer and use it in GitHub Desktop.
Exercise in JS funcition debouncing
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
var debounce = function (func, threshold, execAsap) { | |
var timeout; | |
return function debounced () { | |
var obj = this, args = arguments; | |
function delayed () { | |
if (!execAsap) | |
func.apply(obj, args); | |
timeout = null; | |
}; | |
if (timeout) { | |
console.log("Clearing timeout"); | |
clearTimeout(timeout); | |
} | |
else if (execAsap) | |
func.apply(obj, args); | |
timeout = setTimeout(delayed, threshold || 100); | |
}; | |
}; | |
function logger() { console.log( "Yo"); } | |
var debouncedLogger = debounce( logger, 3000, false); | |
for( var i = 0; i < 10; i++) | |
debouncedLogger(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment