Created
January 21, 2013 01:49
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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