Skip to content

Instantly share code, notes, and snippets.

@pugsley
Last active August 29, 2015 14:01
Show Gist options
  • Save pugsley/f60e7d7600a9b6c71295 to your computer and use it in GitHub Desktop.
Save pugsley/f60e7d7600a9b6c71295 to your computer and use it in GitHub Desktop.
// Based on: http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
function debounce(callback, wait, immediate) {
var timeout;
return function() {
var self = this,
args = arguments;
if (timeout) {
clearTimeout(timeout);
} else if (immediate) {
callback.apply(self, args);
}
timeout = setTimeout(function() {
timeout = null;
if (!immediate) {
callback.apply(self, args);
}
}, wait);
};
}
// Example
// If element is double clicked function will only be executed once
var element = document.getElementById("#some-element");
element.addEventListener("click", debounce(function(e) {
console.log("Clicked!");
}, 1000, true));
// Minified
function debounce(e,t,n){var r;return function(){var i=this,s=arguments;if(r){clearTimeout(r)}else if(n){e.apply(i,s)}r=setTimeout(function(){r=null;if(!n){e.apply(i,s)}},t)}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment