Skip to content

Instantly share code, notes, and snippets.

@jshcrowthe
Created January 26, 2017 22:13
Show Gist options
  • Save jshcrowthe/4339709a4cef83c6cca70be704cab329 to your computer and use it in GitHub Desktop.
Save jshcrowthe/4339709a4cef83c6cca70be704cab329 to your computer and use it in GitHub Desktop.
Javascript Event Throttle (Run function X once every Y ms)
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);
}
};
}
@jshcrowthe
Copy link
Author

Example Usage:

document.addEventListener('mousemove', throttle(function (event) {
  console.log('tick');
}, 1000));

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