Skip to content

Instantly share code, notes, and snippets.

@anselmh
Created December 19, 2013 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anselmh/8038268 to your computer and use it in GitHub Desktop.
Save anselmh/8038268 to your computer and use it in GitHub Desktop.
Better timers with closures and throttling through debouncing methods. By Remy Sharp: http://remysharp.com/2010/07/21/throttling-function-calls/
// Debounce without jQuery
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
// Use Debounce Fn with jQuery
$('input.username').keypress(debounce(function (event) {
// do the Ajax request
}, 250));
// Throttling Function
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);
}
};
}
// Use throttle Fn with jQuery
$('body').on('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