0

I have search-bar (Text Field) component and according to what user types there it updates a list. The issue is that for each character that the user enters the list updates, so if they want to write Learn React the list changes 11 times! I need to do something that delays the function (updateList) calls, let's say make it called every 1 second even if it's called many times in a second. any suggestion.

2 Answers2

0

In Simple Way you can do this:

var debounceTimeout = null;

searchInput.on('change keyup', function(event){
  clearTimeout(debounceTimeout);
  debounceTimeout = setTimeout(searchEvents, 500);
});

also you can handling this by a lot of ways like set a var with bool value, and when success let it false and back to true when search trigger ..etc

Anees Hikmat Abu Hmiad
  • 3,460
  • 2
  • 19
  • 36
0

I create a JSFiddle to show you an example:

https://jsfiddle.net/kmo61q89/

Credits go to David Walsh (https://davidwalsh.name/javascript-debounce-function)

Add this debounce function to your code:

function debounce(func, wait, immediate) {
  var timeout;

  return function executedFunction() {
    var context = this;
    var args = arguments;

    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };

    var callNow = immediate && !timeout;

    clearTimeout(timeout);

    timeout = setTimeout(later, wait);

    if (callNow) func.apply(context, args);
  };
};

Then, add an event listener to your input:

var input = document.getElementById("myInput");

var searchFunction = debounce(function() {
  console.log('seach code here')
}, 250);

input.addEventListener('keyup', searchFunction);
Baral
  • 3,103
  • 2
  • 19
  • 28