Ok, so I do search like in google, you type text in input and it gives you entries instantly. But I don\'t like that. I use something like that $(\"TEXTINPUT\").keyup(
Here's how I usually approach it:
$(function(){
var tiTO, jqXHR;
$('textinput').keyup(function(){
if (tiTO) clearTimeout(tiTO);
if (jqXHR && jqXHR.abort) jqXHR.abort();
tiTO = setTimeout(function(){
jqXHR = $.ajax({....});
//Ajax call to PHP
},2000);
});
});
Each keyup resets the timeout, and aborts any active ajax.
If you use the Underscore Library it's as simple as this:
$("TEXTINPUT").keyup(_.throttle(function () {...}, 150));
Docs from the Underscore site:
throttle _.throttle(function, wait)
Returns a throttled version of the function, that, when invoked repeatedly, will only actually call the wrapped function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.
There is also the debounce function:
debounce _.debounce(function, wait)
Calling a debounced function will postpone its execution until after wait milliseconds have elapsed since the last time the function was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized...
Try :
var time_out;
$("TEXTINPUT").keyup(function(){
clearTimeout(time_out);
time_out = setTimeout(your_function, 500);
}
function your_function()
{
/*CHECK DATABASE*/
}
This function will act somewhat like underscore.js, but without the extra dependency. It'll also pass the scope and arguments it's called with to the wrapped function. Unlike YoannM's answer, this returns a self-contained callback that uses no external variables (EG, use as many times as you want).
function throttle (func, wait) {
return function() {
var that = this,
args = [].slice(arguments);
clearTimeout(func._throttleTimeout);
func._throttleTimeout = setTimeout(function() {
func.apply(that, args);
}, wait);
};
}
And usage would be nearly identical to that of the underscore.js library.
$('input').on('input keyup', throttle(function() {
// ...
}, 100));