Javascript jquery - 如何在搜索条目中建立延迟

sdf*_*for 12 javascript ajax jquery

我有一个ajax搜索框,在每个键击中转到服务器并返回搜索结果.当用户快速键入时,我想只搜索最后一个条目而不是每个键击.否则,个别结果会令人烦恼,并且整个过程会变慢.

例如:如果用户快速键入"自由女神像",我不想搜索"sta","stat","statu"等.

我的jQuery代码的基础是:

$('#searchbox').keyup(function(){
    if (this.value.length > 2) {    
        $.post("remote.php",{'partial':this.value},function(data){
            $("#gen_results").html(data);
        });
    }
});        


<input id="searchbox" />
<div id="gen_results"></div>
Run Code Online (Sandbox Code Playgroud)

gen*_*sis 20

使用setTimeout或jQuery的自动完成插件

var timer;
$('#searchbox').keyup(function(){
    if (this.value.length > 2) {
        if (timer){
                clearTimeout(timer);
        }
        timer = setTimeout(function(){
                $.post("remote.php",{'partial':this.value},function(data){
                $("#gen_results").html(data);
                });
        }, 1000);
    }
});
Run Code Online (Sandbox Code Playgroud)