Kevin Beal
Kevin Beal

Reputation: 10868

In jquery how can I call function when someone hasn't typed in 1 second?

I have a <div> that has a list of items being load()ed into it containing a keyword typed in a text input triggered by keyup(). When I also run a jquery plugin that highlights that keyword in the respective search items on keyup() it slows the page WAY down and can even crash my browser.

So I'm wondering if there is a way that I can only trigger this highlighting function after a person hasn't typed any characters in a second or two and THEN trigger the highlighter. Or is there maybe some way I can keep it at the end of the queue so that it always triggers last?

thx

Upvotes: 0

Views: 111

Answers (3)

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

Use setTimeout to set the function to run after 2s and user clearTimeout to cancel this before the 2s are finished:

var timeoutId;

$("input").keyup(function(){

    if(timeoutId){
      clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(intervalFunc, 2000); 
});

Here's an example: http://jsfiddle.net/tdbsY/

Upvotes: 2

devnull69
devnull69

Reputation: 16584

Keep a global timeout variable like var myTimeout = null;. Inside your keyup() handler, you can start a myTimeout = window.setTimeout(highlight, 1500); and cancel the (previous) timeout if it is still running. Inside the highlight function you reset myTimeout to null again.

Something in the lines of

var myTimeout = null;

$('#whatever').keyup(function() {
   if(myTimeout) clearTimeout(myTimeout);
   ....
   myTimeout = window.setTimeout(highlight, 1500);
});

function highlight() {
   myTimeout = null;
   ...
}

Upvotes: 4

David Hedlund
David Hedlund

Reputation: 129832

You want to use setTimeout to delay the call to highlight, and clearTimeout if a new keystroke is received before that one second has passed:

var timeout;

$('#my-input').keyup(function() {

    // clear previous timeout if there was one
    window.clearTimeout(timeout);

    // set new one
    timeout = setTimeout(function() {

        // make your highlight call here

    }, 1000);

});

Upvotes: 1

Related Questions