Created
September 6, 2012 02:01
-
-
Save faceleg/3649866 to your computer and use it in GitHub Desktop.
JS 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
/** | |
* 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'); | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.