Javascript timer that restarts on key up?
O, so i have a 'live search' ajax search, which currently runs an sql search (via ajax) on each key up.
What i would prefer is to:
run an sql search after a key has not been pressed for say 800 milliseconds
.
So i want to have a timer that is started on key up, if the timer rea开发者_Python百科ches 800ms then the ajax is called, if a new keyup event occurs the timer is restarted
how would i do this?
(function () {
var theTimeout;
function doSearch() {
// Do Search
};
$('#theField').bind('keyup', function () {
clearTimeout(theTimeout);
theTimeout = setTimeout(doSearch, 800);
});
}())
There's an excellent plugin TypeWatch you may take a look at (IIRC StackOverflow uses this for the Users page). Here's a sample usage:
$("#textId").typeWatch({
highlight: true,
wait: 800,
captureLength: -1,
callback: function() {
// changed text
}
});
I had that problem my solution was this:
var doAjax = 0
$("input#name").keyup(function(){
doAjax++;
setTimeout(function(){
doAjax--;
if(doAjax>=1){
return;
}
$.post("do_ajax", { ...
dunno if it is the best solution, but it works :)
精彩评论