Skip to content

Instantly share code, notes, and snippets.

@sinelaw
Created November 13, 2014 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sinelaw/ee17edbb53d398f51e47 to your computer and use it in GitHub Desktop.
Save sinelaw/ee17edbb53d398f51e47 to your computer and use it in GitHub Desktop.
debouncer
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