Wait for function till user stops typing

Youss picture Youss · Apr 12, 2012 · Viewed 15.4k times · Source

I have users making ajax call while typing. The problem is that it makes the call for every letter being typed, so I set timeout like this:

$(input).live('keyup', function(e){

setTimeout(function(){ 

var xx = $(input).val();
doSearch(xx); 

}, 400); 

}); 

It does wait for 400ms but then executes for every keyup. How can I change this to make the ajax call only 'once' about 400ms after the last typed letter?

(I used 'delay' in the past but that doesn't work at all with my script...)

Answer

Gavriel picture Gavriel · Apr 12, 2012
timer = 0;
function mySearch (){ 
    var xx = $(input).val();
    doSearch(xx); 
}
$(input).live('keyup', function(e){
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(mySearch, 400); 
});

it's better to move your function to a named function and call it multiple times, 'cause otherwise you're creating another lambda function on each keyup which is unnecessary and relatively expensive