Skip to content Skip to sidebar Skip to footer

How To Debounce Input With Jquery And Lodash

If you are trying to hide and show children based on an input's value with jQuery it will cause performance issue while typing. To avoid calling the filter function after every cha

Solution 1:

I propose another solution without lodash. Just create a map on page load with your elements (assuming they do not change and are created only once on page load).

$(document).ready(function(){
  var map = {};
  $('.child').each(function(i,el){
    map[$(el).text().toLowerCase()] = $(el);
  });
  $('.child').toggle(false);
  $('#search').on('keyup', function(){
    $('.child').toggle(false);
    var el = map[$(this).val().toLowerCase()];
    if (el)
      $(el).toggle(true);
  });
});

Live preview


Solution 2:

$("#search").on("keyup", _.debounce(filterChildren, 300));

function debounce( fn, threshold ) {
    var timeout;
    return function debounced() {
        if ( timeout ) {
            clearTimeout( timeout );
        }
        function delayed() {
            fn();
            timeout = null;
        }
        timeout = setTimeout( delayed, threshold || 100 );
    };
}

Post a Comment for "How To Debounce Input With Jquery And Lodash"