Skip to content

Instantly share code, notes, and snippets.

@sagiavinash
Created April 28, 2015 17:15
Show Gist options
  • Save sagiavinash/95a1c6e25ba6a0aa2af4 to your computer and use it in GitHub Desktop.
Save sagiavinash/95a1c6e25ba6a0aa2af4 to your computer and use it in GitHub Desktop.
Debounce Snippet - Jquery
(function($) {
$.extend({
debounce : function(fn, timeout, invokeAsap, ctx) {
if(arguments.length == 3 && typeof invokeAsap != 'boolean') {
ctx = invokeAsap;
invokeAsap = false;
}
var timer;
return function() {
var args = arguments;
ctx = ctx || this;
invokeAsap && !timer && fn.apply(ctx, args);
clearTimeout(timer);
timer = setTimeout(function() {
!invokeAsap && fn.apply(ctx, args);
timer = null;
}, timeout);
};
}
})(jQuery);
/* Example:
$(window).on('resize', $.debounce(function() {
// All the taxing stuff you do
}, 250));
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment