Search code examples
javascripttypescriptthrottling

throttle function broke my input live search


I am trying to throttle my html on input when user enters some words into search field there must be a redrawing of the block. When I implemented throttle function into my code, the live search stopped working, now the card redrawing does not happen

    searchInput.addEventListener('input', (event: Event) => {
  searchTerm = (event.target as HTMLTextAreaElement).value.toLowerCase();
  throttle(() => {
    showList();
  }, 100);
});

function throttle(func: Function, ms: number) {
  let isThrottled: boolean = false;
  let savedArgs: any, savedThis: any;

  function wrapper(this: any) {
    if (isThrottled) {
      savedArgs = arguments;
      savedThis = this;
      return;
    }
    func.apply(this, arguments);
    isThrottled = true;

    setTimeout(() => {
      isThrottled = false; // (3)
      if (savedArgs) {
        wrapper.apply(savedThis, savedArgs);
        savedArgs = savedThis = null;
      }
    }, ms);
  }

  return wrapper;
}

Solution

  • Your throttle returns a function. You called throttle() but you didn't use the function it returns.

    You should do something like that

      const throttledShowList = throttle(showList, 100); // <-- Add this
      searchInput.addEventListener('input', (event: Event) => {
      searchTerm = (event.target as HTMLTextAreaElement).value.toLowerCase();
      throttledShowList(); // <-- Replace the previous throttle() call with this
    });
    
    function throttle(func: Function, ms: number) {
      let isThrottled: boolean = false;
      let savedArgs: any, savedThis: any;
    
      function wrapper(this: any) {
        if (isThrottled) {
          savedArgs = arguments;
          savedThis = this;
          return;
        }
        func.apply(this, arguments);
        isThrottled = true;
    
        setTimeout(() => {
          isThrottled = false; // (3)
          if (savedArgs) {
            wrapper.apply(savedThis, savedArgs);
            savedArgs = savedThis = null;
          }
        }, ms);
      }
    
      return wrapper;
    }
    

    That way, you define a throttled version of your function that you call on input