Wait for function till user stops typing

2020-08-22 03:03发布

问题:

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

回答1:

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



回答2:

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.



回答3:

I would think that you could use delay() again in this context as long as you're o.k. with adding a new temporary 'something' to the mix. Would this work for you?

$(input).live('keyup', function(e) {
    if (!$(input).hasClass("outRunningAJob")) {
        var xx = $(input).val();
        $(input).addClass("outRunningAJob");
        doSearch(xx);
        $(input).delay(400).queue(function() {
            $(this).removeClass("outRunningAJob");
            $(this).dequeue();
        });
    }
});


回答4:

I found the following easier to implement:

$(input).on('keyup', function () {
    delay(function () {
        if (input).val() !== '' && $(input).val() !== $(input).attr('searchString')) {
            // make the AJAX call at this time
            // Store the value sent so we can compare when JSON returns
            $(input).attr('searchString', $(input).val());

            namepicker2_Search_Prep(input);
        }
    }, 500);
});

By storing the current string you are able to see that the user has stopped typing. Then you can safely call your function to do what ever processing needs to happen.