Created
February 20, 2022 20:58
-
-
Save hahuaz/be85faf336a3c676471ead3db1e6ccd1 to your computer and use it in GitHub Desktop.
Debounce input event with vanilla js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Debounce input event on vanilla js | |
// let debounceTimer; | |
// function handleInput(e) { | |
// window.clearTimeout(debounceTimer); | |
// debounceTimer = window.setTimeout(() => console.log(e.target.value), 1000); | |
// } | |
// document.querySelector('#input').addEventListener('input', handleInput); | |
// Use higher-order debounce function to debounce an event listener | |
const debounce = (callback, time) => { | |
let debounceTimer; | |
return (e) => { | |
window.clearTimeout(debounceTimer); | |
debounceTimer = window.setTimeout(callback.bind(null, e), time); | |
}; | |
}; | |
function handleInput(e) { | |
console.log(e.target.value); | |
} | |
document | |
.querySelector('#input') | |
.addEventListener('input', debounce(handleInput, 1000)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment