0

I don't understand why this works. wouldn't the >>> let timeoutID <<<< reset the variable each time, so that the timeoutId is always empty? I would put the 'let' outside of this assuming that's the only way it would work. However this works, I just don't get it. This is from a Udemy course. I get everything else. I'm an amateur here, so.....

const debounce = (func, delay = 1000) => {
    let timeoutId;
    return (...args) => {
        if (timeoutId) {
            clearTimeout(timeoutId);
        }
        timeoutId = setTimeout(() => {
            func.apply(null,args);
        },delay)
    };

};
const onInput = event => {
        fetchData(event.target.value);  
};
input.addEventListener('input', debounce(onInput,1000));
  • no, since the input handler is executing the function returned by calling `debounce` ... i.e. the *event handler* is executing `(...args) => {` – Jaromanda X Oct 26 '20 at 22:53
  • think of the code being `input.addEventListener('input', (onInput,1000) => { .... });` – Jaromanda X Oct 26 '20 at 22:55
  • `timeoutId` is captured by the function `(...args) => {` via a closure. When the `debounce` call finishes, the variable `timeoutId` won't be destroyed as it is still captured/referenced by the inner `(...args) =>`. If you call `debounce` two times (using it twice), there will be two `timeoutId` variables in memory that hold different values and will probably remain alive until you close the page – ibrahim mahrir Oct 26 '20 at 22:55
  • This can be confusing at first because when the user presses a key in the `` field, it's not `debounce(onInput,1000)` that runs but the inner function that was returned by it. –  Oct 26 '20 at 22:57
  • thank you guys so much! It's clear now! – tonymiceli Oct 27 '20 at 19:06

0 Answers0