Created
November 13, 2014 14:20
-
-
Save sinelaw/ee17edbb53d398f51e47 to your computer and use it in GitHub Desktop.
debouncer
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
function debounce(f, millis) { | |
var ready = true; | |
var timeoutId; | |
var lastMissed; | |
function resetTimeout(){ | |
window.clearTimeout(timeoutId); | |
timeoutId = window.setTimeout(function() { | |
if (lastMissed) { | |
lastMissed(); | |
} | |
ready = true; | |
}, millis); | |
} | |
return function() { | |
lastMissed = function() { | |
lastMissed = null; | |
f.apply(null, arguments); | |
} | |
if (!ready) { | |
console.log('debounced', f, arguments); | |
resetTimeout(); | |
return; | |
} | |
lastMissed(); | |
ready = false; | |
resetTimeout(); | |
}; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment