- May 2022
-
attacomsian.com attacomsian.com
-
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); });
-
-
-
// Get the input box let input = document.getElementById('my-input'); // Init a timeout variable to be used below let timeout = null; // Listen for keystroke events input.addEventListener('keyup', function (e) { // Clear the timeout if it has already been set. // This will prevent the previous task from executing // if it has been less than <MILLISECONDS> clearTimeout(timeout); // Make a new timeout set to go off in 1000ms (1 second) timeout = setTimeout(function () { console.log('Input Value:', textInput.value); }, 1000); });
let timeout = setTimeout(callback, milliseconds); clearTimeout(timeout);
document.getElementById("id-name"); object.addEventListener('event-name',callback);
-
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); })
-