views:

1122

answers:

2

Hello,

I have a form with an <input type=text /> and I want to call a javascript function after 5 seconds of the last key press, and every time a new key is pressed, this timer should reset and only call the function after 5 seconds.

How can I do this?

I'm using jQuery.

thanks!

+9  A: 

Something like this should get you started:

var timeout;
$('input[type=text]').keypress(function() {
    if(timeout) {
        clearTimeout(timeout);
        timeout = null;
    }

    timeout = setTimeout(myFunction, 5000)
})
Crescent Fresh
that's awesome, thanks!
Paulo
Just remember that the timeout function works in milliseconds. That is why he used 5000.
Kevin Crowell
Technically the setting to null is superfluous.
cletus
A: 

Although it doesn't use jQuery, you could also have a look at the debouncing function described here.

Steve

Steve Harrison