Hiroo17 Hiroo17 - 1 month ago 21
jQuery Question

JQuery delay keyup search

I have this code to hide every

.flip
element except the one I searched for:

var $rows = $('.flip');
$('#search').keyup(function()
{
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function()
{
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});


The problem with this is that it searches every time I release a key. How can I make it to wait until I stopped typing

Thanks!

Answer

Simply use setTimeout

$(document).ready(function() {
  var timer;

  var $rows = $('.flip');
  var $self = $(this);

  $('#search').keyup(function() {
    clearTimeout(timer);

    timer = setTimeout(function() {
      $('#test').text(Math.floor(Math.random() * 1000));
      var val = $.trim($self.val()).replace(/ +/g, ' ').toLowerCase();

      $rows.show().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.indexOf(val);
      }).hide();
    }, 300);
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search"/>
<span id="test"></span>