Created
April 28, 2015 17:15
-
-
Save sagiavinash/95a1c6e25ba6a0aa2af4 to your computer and use it in GitHub Desktop.
Debounce Snippet - Jquery
This file contains hidden or 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
(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