How to debounce input with jquery and lodash

↘锁芯ラ 提交于 2019-12-11 14:01:57

问题


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 character, use the debounce method of lodash.

html

<input id="search" />

<div>
  <div class="child">foo</div>
  <div class="child">bar</div>
  ....
</div>

javasrcript

  var filterChildren = function() {
    var value = $(this).val().toLowerCase();
    $(".child").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
    });    
  };

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

Do not miss to import Lodash and jQuery.

PS: this is part of the answer of the this post: How to hide the parent div if all its child div are hidden?


回答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




回答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 );
    };
}


来源:https://stackoverflow.com/questions/51837825/how-to-debounce-input-with-jquery-and-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!