Reputation: 111080
I'm looking to learn how to build something that detects key-presses in order to throttle a function.
Something like:
var LastKeyPress;
function hitTheServer() {
if LastKeyPress > 2 seconds ago {
hit the server and do stuff
LastKeyPress = now();
}
}
What do you think? Maybe this is built into jQuery? Also, its something that I'd likely use for many functions, and it could be interesting to have this working globally, so I can use less code and apply to several functions. Thoughts?
Thanks
Upvotes: 0
Views: 250
Reputation: 324727
This is relatively simple using window.setTimeout
:
// Example function to be throttled
function throttledFunction() {
alert("Two seconds since last keypress");
}
var keypressTimer = null, keypressDelay = 2000;
document.onkeypress = function() {
if (keypressTimer) {
window.clearTimeout(keypressTimer);
}
keypressTimer = window.setTimeout(function() {
keypressTimer = null;
throttledFunction();
}, keypressDelay);
};
Upvotes: 0
Reputation: 25620
You might check out Ben Alman's jQuery throttle / debounce plugin
Upvotes: 1
Reputation: 57278
I would say like so:
var LastKeyPress;
function hitTheServer(){
n = new Date().getSeconds();
if (LastKeyPress == undefined || LastKeyPress > n+2){
//Code
LastKeyPress = n;
}
}
Upvotes: 1