Skip to content

Instantly share code, notes, and snippets.

@faceleg
Created September 6, 2012 02:01
Show Gist options
  • Save faceleg/3649866 to your computer and use it in GitHub Desktop.
Save faceleg/3649866 to your computer and use it in GitHub Desktop.
JS Debouncer
/**
* Debouncer function to prevent multiple calls from a repeatedly called event
* @link http://stackoverflow.com/a/4298672/187954
* @link https://gist.github.com/3649866
* @param {Function} callback A callback to execute when timeout is reached with no subsequent calls.
* @param {Integer|null} timeout A custom timeout or null for 200
* @return {Function} The debouncer function.
*/
function eventDebouncer(callback, timeout) {
timeout = timeout || 200;
var timeoutID;
return function() {
var scope = this, args = arguments;
window.clearTimeout(timeoutID);
timeoutID = window.setTimeout(function() {
callback.apply(scope, Array.prototype.slice.call(args));
}, timeout);
};
}
// Perform an action on a completed window resize
$(window).resize(debouncer(function(event) {
console.log('resized');
}));
@tristanm
Copy link

I've made a simplified version at https://gist.github.com/3734311 with everything centric to $(document).resize(...) as this is what you're (mostly) wanting to debounce.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment