1

Possible Duplicate:
Run javascript function when user finishes typing instead of on key up?

I wrote a quick live filter that will filter a long list of about ten thousand items. The children of each item have a host of meta data related to them. Descriptions, related documents, usefors, etc. I bring in a letter at a time and filter the page from there. If someone types too quickly the page may not keep up. I might receive then multiple IDS of tag-C if I were to type 'Cam' to quickly.

My question asks is there a way to limit the function call until keystrokes have stopped. Almost a hoverIntent of keystrokes.

Here is a quick fiddle I whipped up showing about what I am after, http://jsfiddle.net/kb8Hw/ But my code is a bit more complex. I have a longer list, limit it to a single letter at a time, and normalize the search string a bit more. Essentially each time this.value[0] changes it returns to the server and grabs a new set of tags. From there I filter whats on the page using jquery.

Community
  • 1
  • 1
matchew
  • 19,195
  • 5
  • 44
  • 48
  • Is this something along the lines of what you want: http://stackoverflow.com/questions/4220126/run-javascript-function-when-user-finishes-typing-instead-of-on-key-up – itsmequinn Feb 23 '12 at 20:48
  • yes, I figured it was asked before. I did search, but wasn't sure of the string. I suppose this should be marked as a dupe. – matchew Feb 23 '12 at 20:51
  • I only knew it existed because I needed it a week ago and looked in my favorites. – itsmequinn Feb 23 '12 at 20:54

2 Answers2

3

Start a timer. Reset it on each keypress. When the user stops typing (300-600 ms is good) the timer will fire. Call your function.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
1

Typically you would use clearTimeout and setTimeout to trigger the real search.

On keyup, instead of doing the search directly, start a timer that will execute the search after 500ms for instance.

The clearTimeout call is there is stop any previous timer that would have been started on the previous keyup (you get a keyup event for each letter that is typed).

Example:

var to;

$('#live-search').on('keyup', '#live-search-box', function() {
    var val = this.value;
    clearTimeout(to);
    to = setTimeout(function() {
        $('#countries').find('span').show();
        if (val) {

            $('#countries').find('span').hide();
            $('#countries').find('span[id^=' + val.toLowerCase() + ']').fadeIn('fast');

        }
    }, 500);
});

DEMO

Didier Ghys
  • 30,396
  • 9
  • 75
  • 81