1

I will use a debounce function as example.

const debounce = (func, wait) => {
  let timeout;

  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };

    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

then I create a dummy function:

const dummy = () => console.log('debounced');

then I create a debouncedDummy function:

const debouncedDummy = debounce(dummy, 1000);

and then I call debouncedDummy multiple times:

debouncedDummy();
debouncedDummy();
debouncedDummy();
debouncedDummy();

What I need help understanding is why timeout variable is shared across multiple calls of debouncedDummy ?
What if timeout was defined outside the scope of debounce ?
What if timeout was defined inside the scope of executedFunction ?

3
  • 2
    "What if timeout was defined outside the scope of debounce ?" in this case, nothing happens. However, if you debounce two different functions, they'll share the same timeout, so debouncedA(); debouncedB(); would not run twice. "What if timeout was defined inside the scope of executedFunction ?" then effectively the function is not debounced. Each time you call debouncedDummy() a new timeout is created, so debouncedDummy(); debouncedDummy(); does not interfere with each other, therefore both execute. Commented Dec 9, 2021 at 12:36
  • 1
    Outside debounce and inside executedFunction Commented Dec 9, 2021 at 12:40
  • @VLAZ Actually the second case, I just found out that falls into "stale closure" category, or rather the inverse of it Commented Dec 9, 2021 at 12:53

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.