Skip to content

Instantly share code, notes, and snippets.

@evanre
Last active October 20, 2017 14:18
Show Gist options
  • Save evanre/b4ac3c3755e7bee57af8d2b24ae44cf2 to your computer and use it in GitHub Desktop.
Save evanre/b4ac3c3755e7bee57af8d2b24ae44cf2 to your computer and use it in GitHub Desktop.
Debounce and throttle function's decorator jQuery plugin
/**
* Debounce and throttle helper function's
*
* https://remysharp.com/2010/07/21/throttling-function-calls
*
* Examples:
* $('input.username').keypress(debounce(function (event) {
* // do the Ajax request
* }, 250));
*
* $('body').on('mousemove', throttle(function (event) {
* console.log('tick');
* }, 1000));
*
*/
(function() {
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
function throttle(fn, threshhold, scope) {
threshhold || (threshhold = 250);
var last,
deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
}
})();
@oalexdoda
Copy link

Do you have a patch to avoid arguments.callee on line 58?

@oalexdoda
Copy link

image

@evanre
Copy link
Author

evanre commented Oct 20, 2017

@alexandrudoda hello, I've update scripts ;-)

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