The method you are referring to is called "Debouncing"
Usually I have the "Debounce" function at the bottom of all my scripts.
var debounce=function(func, threshold, execAsap) { var timeout; return function debounced () { var obj = this, args = arguments; function delayed () { if (!execAsap) func.apply(obj, args); timeout = null; }; if (timeout) clearTimeout(timeout); else if (execAsap) func.apply(obj, args); timeout = setTimeout(delayed, threshold || 100); }; };
And then whenever I do something that can benefit from a debut, I can use it in general
So your code will be rewritten as
$("#s").keyup(debounce(function() { var searchbox = $(this).val(); var dataString = 's='+ searchbox; if(searchbox!='') { $.ajax({ type: "POST", url: "/livesearch.php", data: dataString, cache: false, success: function(html){ $("#display").html(html).show(); } }); } else {return false; } } ,350 ,false ));
ekhaled
source share