Haroldo
Haroldo

Reputation: 37377

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

how would i do this?

Upvotes: 0

Views: 189

Answers (3)

fmsf
fmsf

Reputation: 37137

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", { ...

I don't if it is the best solution, but it works :)

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

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
    }
});

Upvotes: 2

Matt
Matt

Reputation: 75317

(function () {

var theTimeout;

function doSearch() {
  // Do Search
};

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

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

}())

Upvotes: 5

Related Questions