title: JavaScript - Optimizing autocomplete with debounce and throttling
body: <p>I have the following text box and &quot;autocomplete&quot; function. It is supposed to have a debounce of 350 ms after every character is typed in the text box, but it doesn't work.</p>
  <p>Try it for yourself in the JSFiddle. As you can see in the console, the console is logging every character typed without waiting for the debounce time.</p>
  <p>What should I do to make this function work as intended? I want there to be a 350 ms debounce time to prevent every character from being logged... just update the output every 350ms.</p>
  <p>Here is the JSFiddle: <a href="https://jsfiddle.net/8pdb97wj/1/" rel="nofollow noreferrer">https://jsfiddle.net/8pdb97wj/1/</a></p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>$(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(() =&gt; {
        getAutocomplete();
      }, 350);
    });
  });
  
  function getAutocomplete() {
    console.log($('.searchBox').val());
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;input type="text" class="searchBox"&gt;&lt;/input&gt;</code></pre>
  </div>
  </div>
  </p>