2 Matching Annotations
  1. May 2022
    1. let timer; // Timer identifier const waitTime = 500; // Wait time in milliseconds // Search function const search = (text) => { // TODO: Make HTTP Request HERE }; // Listen for `keyup` event const input = document.querySelector('#input-text'); input.addEventListener('keyup', (e) => { const text = e.currentTarget.value; // Clear timer clearTimeout(timer); // Wait for X ms and then process the request timer = setTimeout(() => { search(text); }, waitTime); });

      let timer; // timer identifier const waitTime = 500; // Wait time in milliseconds

      // search function const search = (text) => { // to do: make http request here }

      // Listen for keyup event const input = document.querySelector('#input-text'); input.addEventListener('keyup', (e) => { const text = e.currentTarget.value; // clear timer clearTimeout(timer);

      // Wait for X ms and then process the request timer = setTimeout(() => { search(text); }, waitTime); });

    1. In order to execute an event listener (or any function for that matter) after the user stops typing, we need to know about the two built-in JavaScript methods setTimeout(callback, milliseconds) and clearTimeout(timeout): setTimeout is a JavaScript method that executes a provided function after a specified amount of time (in milliseconds). clearTimeout is a related method that can be used to cancel a timeout that has been queued.

      Step 1. Listen for User Input

      <input type="text" id="my-input" />

      let input = document.querySelector('#my-input'); input.addEventListener('keyup', function (e) { console.log('Value:', input.value); })

      Step2: Debounce Event Handler Function

      let input = document.getElementById('my-input'); let timeout = null;

      input.addEventListener('keyup', function(e) { clearTimeout(timeout);

      timeout = setTimeout(function() { console.llog('Input Value:', textInput.value); }, 1000); })