Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for function till user stops typing

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...)

like image 755
Youss Avatar asked Apr 12 '12 13:04

Youss


2 Answers

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

like image 104
Gavriel Avatar answered Sep 30 '22 13:09

Gavriel


You need to reset the timer each time a new key is pressed, e.g.

(function() {
    var timer = null;

    $(input).live('keyup', function(e) {
        timer = setTimeout(..., 400);
    });

    $(input).live('keydown', function(e) {
        clearTimeout(timer);
    });
)();

The function expression is used to ensure that the timer variable's scope is restricted to those two functions that need it.

like image 28
Alnitak Avatar answered Sep 30 '22 13:09

Alnitak