为什么超时变量在这种情况下是可共享的?

Why is the timeout variable shareable in this case?

answers to this question中有人明智地指出

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

我不太明白。由于超时变量是每次 debounce 调用的本地变量,它不应该是可共享的,不是吗?

p.s。虽然是闭包,但每次调用都应该有不同的闭包,它们只是在母函数之后同时延长它们的生命returns,但它们不应该互相交谈,对吗?

这是另一个问题的函数:

// 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?
     }; 
};

是的,每次调用 debounce 都会得到一组全新的所有内容,但您不会重复调用 debounce。您正在调用 debounce 一次,然后重复调用从 debounce 返回的函数。该函数关闭 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

您只需多次调用 debounce 本身即可设置多个去抖功能(上例中的 gh)。