Skip to content

Instantly share code, notes, and snippets.

@shehi
Created June 27, 2016 09:05
Show Gist options
  • Save shehi/d566a7f1e0db83a231a6e1d386ce3f03 to your computer and use it in GitHub Desktop.
Save shehi/d566a7f1e0db83a231a6e1d386ce3f03 to your computer and use it in GitHub Desktop.
/**
* @usage $('body').on('mousemove', throttle(function (event) {console.log('tick');}, 1000));
*/
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 + last - now);
} else {
last = now;
fn.apply(context, args);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment