Skip to content

Instantly share code, notes, and snippets.

@akshar-dave
Last active November 17, 2021 16:41
Show Gist options
  • Save akshar-dave/8598d71ea47839415685e2da4e5cad00 to your computer and use it in GitHub Desktop.
Save akshar-dave/8598d71ea47839415685e2da4e5cad00 to your computer and use it in GitHub Desktop.
Executes code after a delay, only if current text input is different from the old text

Handle input value change after a delay

This executes code only if current text input is different from the old text. Helpful in reducing the number of api requests for search fields.


Examples

Old: "a" New: "a" Execute: NO

Old: "a" New: "a " Execute: NO

Old: "" New: "a" Execute: YES

Old: "a" New: "ab" Execute: YES

//Handle input field text after user stops typing (300ms delay), and only execute code if there is new text
// Create a new timeout
let inputTimeout = null;
// Create a variable to store old text
let oldInputText = '';
inputField.addEventListener('keyup', function () {
// Clear the timeout on keypress
clearTimeout(inputTimeout);
// Set a new timeout for 300ms
inputTimeout = setTimeout(()=>{
// Get new value from the field, and trim any extra spaces
let newInput = inputField.value.trim();
// If new input is different from oldInputText, execute the following
if(newInput != oldInputText) {
//CODE GOES HERE
console.log(`Old: ${oldInputText}\nNew: ${newInput}`);
};
// Set current text to oldInputText
oldInputText = newInput;
}, 300);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment