views:

27

answers:

3

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

+1  A: 

I would say like so:

var LastKeyPress;
function hitTheServer(){
    n = new Date().getSeconds();
    if (LastKeyPress == undefined || LastKeyPress > n+2){

        //Code

        LastKeyPress = n;
    }
}
RobertPitt
Interesting idea. Problem is it is seconds based. So if the user takes a long pause it fails. I think it should be time based vs second based. Also i think there's a bug with the above. Doesn't seem to work in my testing?
AnApprentice
+1  A: 

You might check out Ben Alman's jQuery throttle / debounce plugin

PetersenDidIt
A: 

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);
};
Tim Down