I have a simple input box. When I write something, I want it to be delayed. The problem I have is after the delay when writing characters very fast it calls the console.log multiple times.
What happened now
I type a
and wait. Then I type b c d
fast and wait. Then e f
fast and wait. It catches up which I don't want. I want it to collect what I type, but not output it until the delay is done.
a
.
.
.
b c d
b c d
b c d
.
.
.
e f
e f
What I want to happen
a
.
.
.
b c d
.
.
.
e f
var searchtimer;
window.addEventListener("DOMContentLoaded", () => {
document.querySelector("#search").addEventListener("input", (e) => {
searchtimer = setTimeout(() => {
console.log(e.target.value);
clearTimeout(searchtimer);
}, 1000);
});
});
<input id="search" type="text">