开发者

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

开发者 https://www.devze.com 2023-03-21 07:00 出处:网络
How can you set the opposite of keyPress, keyup, keydown etc. Something like if the user starts to type something and then stop开发者_如何学Python, after 2 seconds 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开发者_如何学Python, 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消