Search code examples
javascriptjquerylistboxdelaysettimeout

How to use setTimeout / .delay() to wait for typing between characters


I am creating a simple listbox filter that takes the user input and returns the matching results in a listbox via javascript/jquery (roughly 5000+ items in listbox). Here is the code snippet:

var Listbox1 = $('#Listbox1');
var commands = document.getElementById('DatabaseCommandsHidden'); //using js for speed

$('#CommandsFilter').bind('keyup', function() {

Listbox1.children().remove();


for (var i = 0; i < commands.options.length; i++) {
    if (commands.options[i].text.toLowerCase().match($(this).val().toLowerCase())) {
        Listbox1.append($('<option></option>').val(i).html(commands.options[i].text));
    }
}
});

This works pretty well, but slows down somewhat when the 1st/2nd char's are being typed since there are so many items.

I thought a solution I could use would be to add a delay to the textbox that prevents the 'keyup' event from being called until the user stops typing. The problem is, I'm not sure how to do that, or if its even a good idea or not.

Any suggestions/help is greatly appreciated.


Solution

  • You can do a delay like this:

    $('#CommandsFilter').keyup(function() {
      clearTimeout($.data(this, 'timer'));
      var wait = setTimeout(search, 500);
      $(this).data('timer', wait);
    });
    
    function search() {
      var temp = $("<select />");
      for (var i = 0; i < commands.options.length; i++) {
        if (commands.options[i].text.toLowerCase().match($(this).val().toLowerCase())) {
          $('<option></option>', { val: i, html: commands.options[i].text }).appendTo(temp);
        }
      }
      Listbox1.empty().append(temp.children());
    }
    

    This stores a timeout on the element you're typing in, if 500ms (adjust as needed) passes between keystrokes, a search executes. Also this appends the elements in a document fragment then into the DOM (still preserving encoding, etc). Depending on the number of items, this may be a decent performance boost as well.