I was trying to understand how debounce work. In one of the tutorials in the internet I found codel ike this:
const input = document.querySelector("input"); const defaultText = document.getElementById("default"); const debounceText = document.getElementById("debounce"); const updateDebounceText = debounce( (text) => (debounceText.textContent = text), 250 ); input.addEventListener("input", (e) => { defaultText.textContent = e.target.value; updateDebounceText(e.target.value); }); function debounce(callback, delay = 1000) { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => callback(...args),delay); }; }
And here comes my question. Why do I need to create explicit variable for calling this function? Can’t I simply call debounce in Event Listener? I tried doing something like this:
debounce((text) => (debounceText.textContent = text), 2500)(e.target.value);
However it would not work and fire every time I enter new value (with slight delay ,but it wasn’t the delay I enter so I am guessing it simply takes some time to run this code)
Advertisement
Answer
In short, you can’t, it’ll work differently.
Debounce function create a timer and stores it inside the closure.
Every time you call ‘debounced’ function it clear previous setTimeout
before runs new one.
In terms of user expirience it looks like function won’t run until you stop doing something.
But if you re-create the function every time you’ll just lose previous timer.
It means that previously started setTimeout
will be fired because you haven’t cleared it.