jQuerybeast
jQuerybeast

Reputation: 14490

jQuery - When not keyPress(), keyUp() for 2 secs do function()

How can you set the opposite of keyPress, keyup, keydown etc. Something like if the user starts to type something and then stop, after 2 seconds do function(){}

I tried onKeyPress with delay but it doesn't seem to work.

Thanks

Upvotes: 1

Views: 1516

Answers (4)

msbrogli
msbrogli

Reputation: 493

You can use keyPress and a global timer. Just reset the timer every time the user press a key. I guess the code is something like:

var myTimer = undefined;
var delayTime = 2000; // should be in miliseconds.

function myfunction() {
    // do your stuff here
}

function onKeyPress(e) {
    if (myTimer) {
        clearTimeout(myTimer);
    }
    myTimer = setTimeout('myfunction();', delayTime);
}

PS: I have not tested this code.

Upvotes: 2

jfriend00
jfriend00

Reputation: 707238

On a key event, you set a 2 second timer. If another key event comes in before the timer goes off, you stop the timer and set a new one. If the timer fires, then there's been 2 seconds of no typing.

Upvotes: 1

Prasanna
Prasanna

Reputation: 11544

I don't know whether any native way of doing this. But i have used this plugin to perform this.

Upvotes: 0

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239646

Well, one oldschool way to do it is to use setTimeout and clearTimeout. Basically, every time a keypress happens, you cancel the previous timeout, and then set up a new one with a 2 second delay. The function call will only actually go through once someone stops pressing keys for 2 seconds, which I think is what you've asked for

Upvotes: 0

Related Questions