Skip to content

Instantly share code, notes, and snippets.

@ginotria
Created January 21, 2013 01:49
Show Gist options
  • Save ginotria/4583055 to your computer and use it in GitHub Desktop.
Save ginotria/4583055 to your computer and use it in GitHub Desktop.
If you’ve written any kind of validation on user input, like onkeypress then you’ll know that sometimes you want to throttle the amount of times your function runs. A good example of this is Ajax based username validation – you don’t want to hit the server on every key press, because most users will be able to write their name in around 1/10th o…
function throttle(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
$('input.username').keypress(throttle(function (event) {
// do the Ajax request
}, 250));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment