Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement a delay on jQuery keyup?

I'm making a list filter and want a delay in case the user is a fast typer. Looking at different solutions for similar questions hasn't helped me and I don't understand the logic they implement.

This is my current code:

$.fn.filterList = function(){   
    var inputFilter = $(this);
    var list        = $('#' + inputFilter.data('list'));
    var listItems    = list.children('li');

    inputFilter.keyup(function(){

        setTimeout(function () {
            var term = inputFilter.val().toLowerCase();

            listItems.each(function(i, e){
                var city = ($(e).text()).toLowerCase();

                if(city.startsWith(term)){
                    console.log(city);
                }
            });
        }, 800);
    });

};

$('.my-input').filterList();

The problem with this is that it will trigger on each keyup, no matter how fast the user types.

How can I implement a delay so that it does not trigger for each keyup?

like image 625
Steven Avatar asked Jan 20 '26 16:01

Steven


1 Answers

On each successive keypress you need to clear the previous timer so that the function only fires X milliseconds after typing ends. Try this:

var timer;

inputFilter.keyup(function() {
  clearTimeout(timer);
  timer = setTimeout(function() {
    var term = inputFilter.val().toLowerCase();

    listItems.each(function(i, e) {
      var city = $(e).text().toLowerCase();
      if (city.startsWith(term)) {
        console.log(city);
      }
    });
  }, 800);
});

Here's a simplified working example:

var timer;
$('#foo').keypress(function() {
  clearTimeout(timer);
  timer = setTimeout(function() {
    $('div').fadeIn('fast').delay(1000).fadeOut('fast');
  }, 800);
});
div { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="foo" />
<div>You stopped typing 1 second ago</div>
like image 104
Rory McCrossan Avatar answered Jan 23 '26 06:01

Rory McCrossan