简体   繁体   中英

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

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM