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 ?

entropyfeverone
  • 1,052
  • 2
  • 8
  • 20
  • 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. – VLAZ Dec 09 '21 at 12:36
  • 1
    [Outside `debounce`](https://jsbin.com/fuborug/1/edit?js,console) and [inside `executedFunction`](https://jsbin.com/paqocik/1/edit?js,console) – VLAZ Dec 09 '21 at 12:40
  • @VLAZ Actually the second case, I just found out that falls into "stale closure" category, or rather the inverse of it – entropyfeverone Dec 09 '21 at 12:53

0 Answers0