Skip to content

Instantly share code, notes, and snippets.

@etoxin
Created June 28, 2016 01:11
Show Gist options
  • Save etoxin/8895a8f98c09201943dfc92c3572cd83 to your computer and use it in GitHub Desktop.
Save etoxin/8895a8f98c09201943dfc92c3572cd83 to your computer and use it in GitHub Desktop.
/**
* JS Throttle Function
* @example
$('body').on('mousemove', throttle(function (event) {
console.log('tick');
}, 1000));
*
* @param fn {Function} callback function
* @param threshhold {Number} Threshold in milliseconds
* @param scope {object} Scope to pass into function.
* @returns {Function}
*/
throttle: function(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);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment