views:

51

answers:

3

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 reaches 800ms then the ajax is called, if a new keyup event occurs the timer is restarted

how would i do this?

+2  A: 

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
    }
});
Darin Dimitrov
absolutely perfect!
Haroldo
+5  A: 
(function () {

var theTimeout;

function doSearch() {
  // Do Search
};

$('#theField').bind('keyup', function () {
  clearTimeout(theTimeout);

  theTimeout = setTimeout(doSearch, 800);
});

}())
Matt
+1, was just typing a similar solution.
Andy E
+1 for typing the same solution then! :P
Matt
Might be an idea to namespace the global variable too, but it's surely op's job to do it :)
Alex Bagnolini
The variable isn't global, it's in a closure.
Alsciende
A: 

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 :)

fmsf