lodash debounce 忽略 space 键

lodash debounce ignore space key

嗨,我正在使用 lodash .. 一切都很好.. 但我有问题,那就是我希望 debouce 在按下回车键时不工作.. 这是我的 lodash 密钥 ..

search_products:_.debounce(function(event)
{
     // my code here 
    // how can i let debounce work with all keys but not with enter key
},5),

我想要延迟 5ml 不与 enter 一起使用 另外,如果有任何类似 debouce 或任何花药库的其他方法,任何人都可以在这里帮助我 那可能吗 谢谢

您可以提取 debounced 函数,仅在按下 enter 键以外的其他内容时调用它。

{
  search_products: function (event) {
    if (event.code !== 'Enter') {
      debounced(event);
    }
  }
}

const debounced = _.debounce(function(event) {
  // ...
}, 5);

您可以使用 flush() method included with lodash debounce

flush 将立即调用所有延迟的函数调用。

在下面输入,会有 1 秒的延迟,但按回车键,它会立即记录结果。

const debounced = _.debounce(value => {
  console.log(value);
}, 1000);

const handler = event => {
  if (event.key === 'Enter') return debounced.flush();

  debounced(event.target.value);
}

document.querySelector('input').addEventListener('keyup', handler);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<input type="text" placeholder="type something">