油门功能破坏了我的输入实时搜索

throttle function broke my input live search

我试图限制我的 html 输入,当用户在搜索字段中输入一些词时,必须重新绘制块。当我在我的代码中实现节流功能时,实时搜索停止工作,现在卡片重绘不会发生

    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;
}

你的throttlereturns一个函数。你调用了 throttle() 但你没有使用它的函数 returns.

你应该这样做

  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;
}

这样,您就定义了一个在输入时调用的函数的节流版本