0

In the answers to this question someone wisely points out that

The timeout variable stays accessible during every call of the produced function even after debounce itself has returned, and can change over different calls.

It doesn't quite make sense to me. As the timeout variable is local to each call of debounce, it shouldn't be shareable, isn't it?

p.s. Even though it is closure, each call should have a different closure, they just simultaneously all extend their lives after the mother function returns, but they shouldn't talk to each other, right?

Here's the function from the other question:

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
function debounce(func, wait, immediate) {
    var timeout;              //Why is this set to nothing?
    return function() {
        var context = this, 
        args = arguments;
        clearTimeout(timeout);   // If timeout was just set to nothing, what can be cleared? 
        timeout = setTimeout(function() {
             timeout = null;
             if (!immediate) func.apply(context, args);
        }, wait);
        if (immediate && !timeout) func.apply(context, args);  //This applies the original function to the context and to these arguments?
     }; 
};
Community
  • 1
  • 1
Jinghui Niu
  • 990
  • 11
  • 28

1 Answers1

2

Yes, each call of debounce will get a fresh set of everything, but you are not repeatedly calling debounce. You are calling debounce once and then repeatedly call the function that was returned from debounce. That function closes over timeout.

var f = debounce(func, wait, immediate);
f();  // won't call func immediately
f();  // still won't call func 
// wait a while, now func will be called

You would only call debounce itself multiple times to set up multiple debounced functions (a g and h in the above example).

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 1
    Is there a practical use for the "context" variable? In my debugging test, the "context" variable always refers to the Window object. I guess it's because of the fact that it's an anonymous function. Could it be of other use? Thanks. – Jinghui Niu Aug 03 '16 at 03:53
  • 1
    I suppose you could assign the returned closure to an object, and that object would become `this` in the original `func`: `var x = { f : debounce(func,w,i) }; x.f(); }` – Thilo Aug 03 '16 at 03:56
  • Or just supply it when calling `f`: `f.apply(someObjectThatNeedsToBecomeThisInFunc)`. – Thilo Aug 03 '16 at 03:57
  • So this is useful if `func` was a "method" not just a bare function. – Thilo Aug 03 '16 at 03:58