I have the following code:
$("#test").on("keyup", (e) => {
if(e.target.value.length === 3) {
setTimeout(() => {
console.log("fired")
}, 2000)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test">
If the user enters 3 characters, console.log("fired") gets automatically fired after 2 seconds (That works with the above code)
But if the user types another character during this time, I need to be able to clear the old time out and wait for 2 seconds again.
Once this times out, it should just run as expected. How can I achieve this?
EDIT:
let timeOut;
$("#test").on("keyup", (e) => {
if(e.target.value.length === 3) {
timeOut = setTimeout(() => {
console.log("fired if length is 3")
}, 2000)
} else if (e.target.value.length === 4) {
clearTimeout(timeOut)
timeOut = setTimeout(() => {
console.log("fired if length is 4")
}, 2000)
}
})
clearTimeoutvar timeout. Then useclearTimeout(timeout)to remove the existing timer, andtimeout = setTimeout(...)to restart it.clearTimeoutas described by you and @TylerRoper