-
-
Save ncou/35292e7bfa547d6a9000570d7c4a5198 to your computer and use it in GitHub Desktop.
Debounce and throttle function's decorator jQuery plugin
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
/** | |
* Debounce and throttle function's decorator plugin 1.0.5 | |
* | |
* Copyright (c) 2009 Filatov Dmitry ([email protected]) | |
* Dual licensed under the MIT and GPL licenses: | |
* http://www.opensource.org/licenses/mit-license.php | |
* http://www.gnu.org/licenses/gpl.html | |
* https://habrahabr.ru/post/60957/ | |
* | |
*/ | |
(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); | |
}; | |
}, | |
throttle : function(fn, timeout, ctx) { | |
var timer, args, needInvoke; | |
return function() { | |
args = arguments; | |
needInvoke = true; | |
ctx = ctx || this; | |
if(!timer) { | |
(function() { | |
if(needInvoke) { | |
fn.apply(ctx, args); | |
needInvoke = false; | |
timer = setTimeout(arguments.callee, timeout); | |
} | |
else { | |
timer = null; | |
} | |
})(); | |
} | |
}; | |
} | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment