AnApprentice
AnApprentice

Reputation: 111080

jQuery - Limiting server hits based on Last Key Press?

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

Answers (3)

Tim Down
Tim Down

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

PetersenDidIt
PetersenDidIt

Reputation: 25620

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

Upvotes: 1

RobertPitt
RobertPitt

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

Related Questions