Matej Tymes Matej Tymes - 1 month ago 7
Javascript Question

Run function after user has stopped typing

I have an input field in which user can input a long value. This value is then used as input value in a complex time consuming function.

My question is: how can I start execution of this function approximately 1 second after the user finished his typing? (I don't want to run it after each key press as it is really slowing the page). So if his next keystroke is in the 1s limit from the last key stroke, than wait additional second.

Do you have any suggestions?

additional note: I also need to pass some parameters into this function

Answer

Here's a rough draft : http://jsfiddle.net/jomanlk/msmJp/

Uses setTimeout and clearTimeout

<input type='text' id='text'>

var timer = null;
$('#text').keydown(function(){
       clearTimeout(timer); 
       timer = setTimeout(doStuff, 1000)
});

function doStuff() {
    alert('do stuff');
}
Comments