Wait for function till user stops typing

旧巷老猫 提交于 2019-12-05 02:05:44
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

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.

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();
        });
    }
});

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!