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.
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
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">
Your expected behavior looks like debounce
.
It seems to me that you should clearTimeout
before creating the new one.
var searchtimer;
window.addEventListener("DOMContentLoaded", () => {
document.querySelector("#search").addEventListener("input", (e) => {
clearTimeout(searchtimer); // <--- The solution is here
searchtimer = setTimeout(() => {
console.log(e.target.value);
}, 1000);
});
});
<input id="search" type="text">
clearTimeout(searchtimer);
Read post "throttleTime vs debounceTime in RxJS" to understand in detail.