JavaScript - 通过去抖动和节流优化自动完成

JavaScript - Optimizing autocomplete with debounce and throttling

我有以下文本框和“自动完成”功能。它应该在文本框中输入每个字符后有 350 毫秒的去抖动,但它不起作用。

在 JSFiddle 中亲自尝试一下。正如您在控制台中看到的那样,控制台正在记录输入的每个字符,而无需等待去抖动时间。

我应该怎么做才能使此功能按预期工作?我希望有 350 毫秒的去抖动时间以防止记录每个字符...只需每 350 毫秒更新一次输出。

这是 JSFiddle:https://jsfiddle.net/8pdb97wj/1/

$(document).ready(function() {
  let debounce;
  $('.searchBox').on('keydown', function(e) {
    // get keycode of current keypress event
    var code = (e.keyCode || e.which);

    // do nothing if it's an arrow key or enter
    if (code == 37 || code == 38 || code == 39 || code == 40 || code == 13) {
      return;
    }

    // do normal behavior for any other key
    debounce = setTimeout(() => {
      getAutocomplete();
    }, 350);
  });
});

function getAutocomplete() {
  console.log($('.searchBox').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="searchBox"></input>

在设置另一个之前清除现有超时。

$(document).ready(function() {
  let debounce;
  $('.searchBox').on('keydown', function(e) {
    // get keycode of current keypress event
    var code = (e.keyCode || e.which);

    // do nothing if it's an arrow key or enter
    if (code == 37 || code == 38 || code == 39 || code == 40 || code == 13) {
      return;
    }

    // do normal behavior for any other key
    clearTimeout(debounce);
    debounce = setTimeout(() => {
      getAutocomplete();
    }, 350);
  });
});

function getAutocomplete() {
  console.log($('.searchBox').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="searchBox">