Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript jquery - How do I build a delay into the search entry

I have an ajax search box that goes to the server on every key stroke and returns the result of the search. When the user types quickly, I want to search only on the last entry and not on every key stroke. Otherwise the individual results flash annoyingly and the whole process is slowed.

For example: if the user types "statue of liberty" quickly, I don't want to search on "sta", "stat", "statu" etc.

the basics of my jQuery code is:

$('#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>
like image 834
sdfor Avatar asked Aug 12 '11 16:08

sdfor


1 Answers

use setTimeout or jQuery's autocomplete plugin

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);
    }
});
like image 178
genesis Avatar answered Sep 30 '22 05:09

genesis